Skip to content

Release steps (one-time) ​

Every first-deploy note and every gated repair this project has written, verbatim, with the migration or release it belongs to and whether it has run.

This page is a log, not a runbook. Each step below belongs to ONE release and runs once per environment. The procedure that is true on any day — topology, shipping, the deploy pipeline, staging, versioning, the migrations procedure, the crontab, backup, verification and operations — is in Deployment & server ops, and one-time steps never go back there: scripts/runbook-split.test.ts fails the build if one does, and fails if an entry here has no executed: status.

Reading the executed: field ​

ValueMeans
YYYY-MM-DDthe step ran on prod on that date, and the repo proves it
pendingthe migration or release it belongs to has not shipped yet
outstandingthe release SHIPPED, and the repo shows the gated prod step has not been taken
unverifiedit probably ran, and nothing in the repository says so

pending and outstanding are different questions: a gated step can be waiting on an operator long after its code is live on prod, and calling that pending would read as "not released yet" and calling it unverified would throw away evidence the repository actually holds.

unverified is the honest default, not a shrug: prod's onchain_credit.schema_migrations is the only authority on which migrations have been applied, and a repository cannot see it. To settle one, read the ledger on the box:

bash
sudo -u postgres psql -d creddit -c \
  "SELECT filename, applied_at FROM onchain_credit.schema_migrations ORDER BY filename"

and set the date here. A gated repair leaves no ledger row at all; its evidence is the report the run printed, which each step below names.

Fund-size corrections ​

EarnETH TVL restatement (issue #626) ​

  • belongs to: the EarnETH total-shares fix, issue #626
  • executed: 2026-10-06

This release changes EarnETH's fund size to include shares already priced and claimable, consistent with EarnUSD. Its previously published size was understated by a time-varying 1.2–15% in the issue's samples. The historical repair reads totalShares() at each priced snapshot's stored block, never a fixed multiplier or today's share count. It updates only EarnETH's total_supply and updated_at; share rates, returns, timestamps and other tokens are preserved. Rows without a positive share rate are unpublished placeholders, have no TVL to restate, and are excluded (including pre-deployment blocks where the contract does not yet exist). Deposits still awaiting pricing are excluded by the share getter.

Order: deploy the fixed code first (so later refreshes stay correct), then run the repair. No migration is needed. Run against staging after its feature merge; production requires explicit approval after the release deploy. Do not merge the production release or write its database without that approval. The release PR must carry Fixes #626 so the issue closes when it reaches main.

Prerequisites: SSH to root@dexhq.io, installed dependencies from that deploy, and ETHEREUM_ARCHIVE_RPC_URL in the selected checkout's .env.local pointing to an archive endpoint with quota for one call per historical row. The wrapper sources that file and logs to /tmp/onchain-credit-cron/<checkout>-restate-earneth-supply.log. The script defaults to dry run, rejects unknown flags and refuses writes without --execute --confirm-db=<actual database>. It checks current_database(), including on a dry run with --confirm-db, before selecting history.

1. Select the environment. For authorized staging validation:

bash
cd /opt/onchain-credit-staging
EARNETH_DB=creddit_staging
EARNETH_RUN=/root/earneth-626-staging-$(date -u +%Y%m%dT%H%M%SZ)
mkdir -p "$EARNETH_RUN"

For production only after approval and release deploy, use this block instead:

bash
cd /opt/onchain-credit
EARNETH_DB=creddit
EARNETH_RUN=/root/earneth-626-prod-$(date -u +%Y%m%dT%H%M%SZ)
mkdir -p "$EARNETH_RUN"

2. Record the deployed commit, back up the source rows, and record rate inputs. Keep the directory until the release after next. EARNETH_END fixes the validation range so a later cron insertion does not change the comparison.

bash
git rev-parse HEAD > "$EARNETH_RUN/commit.txt"
EARNETH_END=$(sudo -u postgres psql -d "$EARNETH_DB" -Atc "SELECT max(snapshot_ts) FROM onchain_credit.token_yield_apy WHERE token_address = '0xbbfc8683c8fe8cf73777fede7ab9574935fea0a4'")
test -n "$EARNETH_END"
printf '%s\n' "$EARNETH_END" > "$EARNETH_RUN/end.txt"
sudo -u postgres psql -d "$EARNETH_DB" -c "COPY (SELECT * FROM onchain_credit.token_yield_apy WHERE token_address = '0xbbfc8683c8fe8cf73777fede7ab9574935fea0a4' AND snapshot_ts <= '$EARNETH_END' ORDER BY snapshot_ts) TO STDOUT WITH CSV HEADER" > "$EARNETH_RUN/before.csv"
sudo -u postgres psql -d "$EARNETH_DB" -Atc "SELECT snapshot_ts, block_at_snapshot, share_rate, supply_apy, apy_30d FROM onchain_credit.token_yield_apy WHERE token_address = '0xbbfc8683c8fe8cf73777fede7ab9574935fea0a4' AND snapshot_ts <= '$EARNETH_END' ORDER BY snapshot_ts" > "$EARNETH_RUN/rates-before.txt"
scripts/run-cron.sh repair/restate-earneth-supply.ts --confirm-db="$EARNETH_DB"
cp "/tmp/onchain-credit-cron/$(basename "$PWD")-restate-earneth-supply.log" "$EARNETH_RUN/dry.log"
tail -1 "$EARNETH_RUN/dry.log"

The last line must be DRY RUN db=<selected database> and name rows, changed, unchanged, failed and unanchored. Read the would write lines: each must name its stored block. Stop on failed or unanchored above zero. An unanchored row cannot be repaired without establishing its historical block separately; do not guess one or declare the whole history repaired. The script exits non-zero for either condition.

3. Apply and verify the whole history.

bash
scripts/run-cron.sh repair/restate-earneth-supply.ts --execute --confirm-db="$EARNETH_DB"
cp "/tmp/onchain-credit-cron/$(basename "$PWD")-restate-earneth-supply.log" "$EARNETH_RUN/apply.log"
tail -1 "$EARNETH_RUN/apply.log"
scripts/run-cron.sh repair/restate-earneth-supply.ts --confirm-db="$EARNETH_DB"
cp "/tmp/onchain-credit-cron/$(basename "$PWD")-restate-earneth-supply.log" "$EARNETH_RUN/verify.log"
tail -1 "$EARNETH_RUN/verify.log"
sudo -u postgres psql -d "$EARNETH_DB" -Atc "SELECT snapshot_ts, block_at_snapshot, share_rate, supply_apy, apy_30d FROM onchain_credit.token_yield_apy WHERE token_address = '0xbbfc8683c8fe8cf73777fede7ab9574935fea0a4' AND snapshot_ts <= '$EARNETH_END' ORDER BY snapshot_ts" > "$EARNETH_RUN/rates-after.txt"
cmp "$EARNETH_RUN/rates-before.txt" "$EARNETH_RUN/rates-after.txt"
sudo -u postgres psql -d "$EARNETH_DB" -c "SELECT snapshot_ts, block_at_snapshot, total_supply, share_rate, total_supply * share_rate AS tvl_eth FROM onchain_credit.token_yield_apy WHERE token_address = '0xbbfc8683c8fe8cf73777fede7ab9574935fea0a4' ORDER BY snapshot_ts DESC LIMIT 8"

Done when verification reports changed=0, failed=0, unanchored=0 (JSON fields in the summary), every row is unchanged, and cmp succeeds. Every row has then been compared to a fresh archive read, not merely checked for non-NULL supply. If interrupted or partially failed, rerun step 3 with the same environment: already-correct rows incur reads but no writes, including no updated_at change; only outstanding counts are written. A concurrent change to a row's count or block fails that row's update and asks for a rerun. No cron pause is necessary.

Allow the funds page's normal ISR interval to expire after the repair, then validate /multi-strategy-funds on staging with its automated smoke. The live size and historical chart now use the same share basis; a live read can differ from the latest history because it is a later block. The nightly staging reseed can restore pre-release production history, so rerun this repair after a reseed until production has been repaired too.

Record: keep staging and production evidence separate. Add the commit and apply/verification summaries here after each run. Set executed: to the proven production date only once that repair has completed; if the production release ships first, change it to outstanding. Production deployment and backfill are completed on 2026-10-06.

Execution evidence, 2026-10-06:

  • Staging: deployed 39357088295e1604a4775b3fc6de2355aca12a23, database creddit_staging, backup /root/earneth-626-staging-20261006T104418Z. Dry run and apply: 981 priced rows, 831 corrected, 150 already correct, failed=0, unanchored=0. Fresh archive verification: changed=0, unchanged=981, failed=0, unanchored=0; rate-input comparison passed. The 1,031 unpriced placeholders were excluded. Staging evidence.
  • Production: v0.80.0 release, release PR #1044, merge d88a91ed5eaa1a38338fa934e3b42e1310a3bd05, database creddit. Backup and execution logs: /root/earneth-626-prod-20261006T134818Z (commit.txt, before.csv, rates-before.txt, rates-after.txt, placeholders-before.csv, placeholders-after.csv, dry.log, apply.log, verify.log). Dry run and apply: 983 priced rows, 833 corrected, 150 already correct, failed=0, unanchored=0. Fresh archive verification: changed=0, unchanged=983, failed=0, unanchored=0. Both rate-input and full unpriced-placeholder comparisons passed byte-for-byte: timestamps, blocks, share rates, supply APY, 30-day APY and all 1,031 excluded placeholders are unchanged.
  • Serving freshness: production deploy run 37472562335 succeeded before the repair, then its same-SHA attempt 2 succeeded after the repair to re-prerender ISR against corrected history. Post-refresh health was ok=true, db=up; app, event ingester and ledger worker restarted on the released code. No migration or unrelated historical repair was performed.

Per-migration first-deploy steps ​

Ordered by migration number, which is the order they were applied.

AI assistant migrations 038 / 039, and the 044 coordinated migration ​

  • belongs to: migrations 038 / 039 / 044 (chat assistant, chat profile, portfolio Fluid) — v0.3.0
  • executed: unverified

This is the ONE heading on this page that was changed beyond a level shift. In the runbook it read simply Migrations, under the assistant section that gave it its subject; standing alone in a log it named nothing, and it collided with the runbook's own evergreen Migrations section, which would have made one of the two resolve as #migrations-1. The body below is verbatim.

038-chat-assistant.sql + 039-chat-profile.sql are additive and auto-apply on the staging deploy (migrate.sh); on prod run migrate.sh by hand after the release, per §4 Migrations.

044-portfolio-fluid.sql (FWS3) is spent, but it still RUNS. It widened portfolio_flow_events and created fluid_event_log + fluid_event_coverage; migration 095 drops all three, and Fluid positions are derived from the ingested event store like every other venue (the retirement runbook). The two files are tagged differently, so a new environment gets both halves and keeps the first: 044 carries no -- DESTRUCTIVE tag, so scripts/ops/migrate.sh and scripts/fixture/build.sh apply it like any other pending file, while 095 carries the tag on line 1, so the fixture build always skips it and migrate.sh skips it until a hand-run --allow-destructive. A fresh database therefore holds the three relations, unread and unwritten, until somebody runs the drop by hand.

048-account-wallets.sql (portfolio multi-wallet) ​

  • belongs to: migration 048 (portfolio multi-wallet) — v0.9.0
  • executed: unverified

Additive and idempotent, so it auto-applies on the staging deploy and is the usual gated manual migrate.sh run on prod after the release. Unlike 044, it needs no special ordering: this release's code is written to run against the pre-048 schema.

That is deliberate, and it is what makes 048 boring. The deploy ships code before schema (staging builds and restarts before migrate.sh; prod migrations are a manual step after the release deploy), and every /api/portfolio/* route resolves its wallet through account_wallets. Left untreated, that window would have taken the whole portfolio surface down with a 500, not just the multi-wallet parts. So the three read paths tolerate a missing table (42P01) and degrade to exactly the pre-multi-wallet behaviour:

PathPre-048 behaviour
resolveWalletSelection (all five portfolio routes)The account sees its own wallet. ?wallet=<other> is still a 403, never a 500.
GET /api/portfolio/walletsReturns the account's own wallet, alone.
loadEligibleWallets (the 6h cron)Falls back to the pre-048 predicate with a loud console.warn, so a tick landing in the window does not punch a hole in every wallet's history.
/api/auth/verify -> ensureSelfWalletRowInside the route's existing best-effort block: logged and swallowed, so sign-in is unaffected.

Only "relation does not exist" is swallowed. A permission error or a syntax error still throws, so a real fault cannot masquerade as "you have one wallet" (verified against a pre-048 database, and pinned by unit tests).

After migrate.sh runs, the next request and the next cron tick pick up the new behaviour with no restart. The scrub must go with it: scrub-staging-pii.sql now TRUNCATEs account_wallets in the same statement as accounts (Postgres refuses to truncate an FK-referenced table unless every referrer is in the same statement), so a staging box running the new SQL against an old checkout, or vice versa, is the one combination to avoid. Migration 056 widens this: it adds ON DELETE CASCADE FKs from the chat tables and portfolio_wallet_index to accounts, so once 056 is applied the reseed's TRUNCATE accounts requires the chat tables and portfolio_wallet_index in the same statement too — which the shipped scrub already does. Apply 056 with migrate.sh (it first deletes any orphaned uid/wallet rows so the constraints validate) and keep the scrub on the box in lockstep; an old scrub against a 056 database fails the reseed closed (safe, but it blocks the nightly reseed until the checkout is current).

Portfolio taxonomy: first deploy (migrations 049 / 050 / 052) ​

  • belongs to: migrations 049 / 050 / 052 (portfolio taxonomy) — v0.10.0
  • executed: unverified

The taxonomy release ships five new cron jobs, three migrations and two exhaustive universe ingests. The ordering below is not cosmetic — each step is what makes the next one correct.

  1. Migrate first: 049, 050, 052. Additive and idempotent. refresh-portfolio.ts degrades gracefully if 049/052 are missing (empty wallet universe, static erc4626 set) but the WS5 backfill refuses to run against a degraded registry rather than mis-reading a wallet-venue-only holder as empty and pruning its history — so until these are applied, backfills abort loudly. That is intentional.
    bash
    cd /opt/onchain-credit && scripts/ops/migrate.sh creddit    # BARE DB NAME
  2. Deep-ingest the two universes, once, by hand, before adding their crons. The first run walks the whole history and takes far longer than a daily tick:
    bash
    MORPHO_UNIVERSE_FROM_BLOCK=<morpho-blue-deploy>   scripts/run-cron.sh refresh-morpho-universe.ts
    METAMORPHO_FACTORY_FROM_BLOCK=<v1.0-factory-deploy> scripts/run-cron.sh refresh-metamorpho-factory.ts
    Steady-state runs scan only new blocks from the cursor, so the env overrides are for the FIRST run only.
  3. One-time full reconcile over every seeded wallet. Required, and easy to miss. Migration 050 seeds a discovery watermark for every historically-active wallet — which authorises the loader to BOUND that wallet's reads. (Since the coverage hardening the authorising artifact is the CERTIFICATE on accounts, migration 061, and it must also be FRESH; the reasoning below is unchanged.) But the seed is derived from pre-T4 history, when the flow scans only admitted CURATED markets/vaults, so it cannot contain a wallet's dormant position in a previously-uncurated market, vault or fToken. Those positions now exist in the universe but not in the index. The weekly reconcile finds them eventually, but at PORTFOLIO_RECONCILE_MAX=50 LRU that is "within N weeks", not "within a week" — and each one fires a drift alert whose remediation text ("investigate discovery.ts") is misleading, because this is expected deploy-time state, not a discovery bug. So after step 2:
    bash
    PORTFOLIO_RECONCILE_MAX=100000 scripts/run-cron.sh refresh-portfolio-reconcile.ts
    
    > Since the coverage hardening this run **exits non-zero and pages** if it finds any aged divergence or dangling link. On the one-time flush that is expected: the whole point is to find and repair pre-existing drift. Read the first alert as the flush's REPORT, not as a cron failure.
    Expect drift rows on this run (that is the point) and none afterwards. The alternative is to drop every seeded watermark and let the /10min enrollment drain re-enroll against the widened universe; either is fine, doing neither is not.
  4. Add the crontab entries (the table is in the runbook: Running a cron/refresher by hand).
  5. Re-run the deploy so the prerendered pages build against the now-complete data (see the ISR note in the runbook).

Migration 061 (discovery completeness certificates) ​

  • belongs to: migration 061 (discovery completeness certificates) — v0.21.0
  • executed: unverified

Additive and idempotent, so staging auto-applies it; prod stays the gated manual step and must run before the release merge. It adds accounts.discovery_scanned_block / discovery_scanned_at / discovery_reconciled_at and copies the surviving portfolio:discover:<wallet> scope rows onto them, taking chain_scan_cursors.updated_at and never now() (a now() stamp would launder every currently-poisoned wallet as freshly certified, which is the whole point of the migration).

Expect one transient after it runs, and it is by design. The copied stamps are as old as the migration-050 seed for most wallets, i.e. far past the 18h staleness horizon, so the whole population is DEMOTED on the first read afterwards. Because the discovery bound fails open for the whole batch, one un-fresh wallet puts every wallet on a full-universe read: expect the 6h tick to log discovery FULL (unscanned wallets) and take measurably longer for a tick or two. It resolves itself as the */10 enrollment drain certifies wallets (PORTFOLIO_ENROLL_MAX, default 10 per run), and the reads are correct throughout, just slower. To shorten it, run the drain by hand right after the migration:

bash
cd /opt/onchain-credit && PORTFOLIO_ENROLL_MAX=50 scripts/run-cron.sh refresh-portfolio-discovery.ts

Deploy order was tolerant in both directions when this shipped: before the migration the readers fell back to the legacy scope-row presence test (whole-batch, on a 42703), and the enrollment / reconcile / backfill writers dual-wrote the scope row so a code rollback still found a current watermark. Both shims are gone and migration 106 deletes the scope rows.

Migrations 062 / 063 (coverage hardening, additive) ​

  • belongs to: migrations 062 / 063 (coverage hardening) — v0.21.0
  • executed: unverified

062 adds a (chain_id, snapshot_ts DESC) index on portfolio_position_snapshots (the 6h tick's derived population asks "which wallets have any snapshot in the last 48h?", and every existing index leads with (chain_id, wallet, …)). 063 adds portfolio_backfill_state.covered_through_ts / covered_through_block, the durable coverage anchor.

Both are additive, idempotent and inert under a code rollback, so staging auto-applies them and prod is the usual gated manual step. Neither has a transient, unlike 061. But 063 is a HARD PREREQUISITE FOR THE DEPLOY, not a post-deploy step: the add-wallet path's requeue statement references covered_through_ts, and although it falls back to the pre-063 predicate on a 42703, the fallback costs a round trip on every add until the migration lands. Apply 063 BEFORE the release merge (the v0.9.0 lesson). with no 063 columns loadCoverageAnchor returns null and every backfill takes the fresh-replay path it takes today. Note the consequence: no wallet gets a gap patch until it has completed one run after 063, because an anchor is only written on a terminal done (or advanced by a tick). That is intentional — a wallet whose last completed replay predates the column has no trustworthy seam to patch from.

Portfolio 100k scale: Phase C envs + the snapshot repartition (migration 067) ​

  • belongs to: migration 067 (snapshot repartition) — v0.25.0
  • executed: unverified

New envs (all optional, safe defaults; set in .env.local on the box):

EnvDefaultEffect
BACKFILL_WORKERS4concurrent wallet backfills per drain invocation (D3), each a separate child process
BACKFILL_GRID_CONCURRENCY6concurrent per-grid-point archive reads within one replay child (D2)
WALLET_TOPIC_CHUNK500wallets per getLogs owner-topic pass in the registration probe's chain scans (D5)
PORTFOLIO_WRITE_LOCK_WAIT_MS600000how long a history writer may QUEUE for the shared advisory key before its acquire is cancelled. Raised for the acquire only; the role's statement_timeout is handed back before any write runs under it. Keep it below CHILD_TIMEOUT_MS (30 min) so a pathological queue reports a failure instead of being SIGKILLed. A typo falls back to the default, never to "wait forever".
DUNE_RATE_LIMIT_COOLOFF_MS60000how long a Dune 429 pauses this process's price-mirror executions (the rate-limit breaker). 0 disables it.
JIT_LEDGER_LAG_BLOCKS40the JIT POSITIONS fast path's freshness gate (D4b). The default keeps it OFF — the ingester's 64-block margin means the tip trails head by ≥ 64, which is not within 40, so a page load full-reads positions. Raise it above ~64 (accepting up to that-many blocks of position staleness, self-healing on the next refresh) to opt in. Production has since opted in (200); the current setting is documented in Environment variables. It gates no WRITE: the page load's ledger merge is unconditional and clamps its own top to how far ingestion has finished.

Effective archive concurrency = BACKFILL_WORKERS × BACKFILL_GRID_CONCURRENCY (default 4 × 6 = 24 concurrent grid reads, each firing several multicall/block requests → ~100–300 concurrent archive requests worst case). The two knobs MULTIPLY: the grid cap is per replay child, the worker pool runs that many children as separate processes, and there is no shared in-process RPC semaphore (finding 7). Size them against a provisioned high-throughput archive endpoint (Alchemy ETHEREUM_ARCHIVE_RPC_URL); on a free-tier archive default the burst rate-limits and grid reads fail → M9 abort → requeue → the same burst next tick. Raising BACKFILL_GRID_CONCURRENCY in isolation is a hidden ×BACKFILL_WORKERS.

The D1 registration-probe discovery and the D4b JIT positions fast path are gated by event_coverage being live back to the read window, so they self-disable until the one-time backfill + ingester have caught the ledger up. The probe falls back to a chain scan when coverage is short; the positions path falls back to a full read.

Snapshot repartition (migration 067, -- DESTRUCTIVE, MANUAL). 067 repartitions portfolio_position_snapshots into monthly range partitions. It is tagged -- DESTRUCTIVE, so the staging auto-apply and a plain migrate.sh SKIP it; it runs only under --allow-destructive. It renames the live table aside to portfolio_position_snapshots_preswap — including its index names, because a table rename leaves those behind and CREATE INDEX IF NOT EXISTS matches on name, so without that the new parent would silently end up with nothing but its PK — builds the partitioned replacement (identical columns / PK / indexes / FK / grants — the PK already carries snapshot_ts, so no conflict target changes), copies every row, and KEEPS _preswap for a manual DROP. Run it while the spine is near-empty (post-reset, the plan's clean-slate timing). The writers auto-create future month partitions at runtime (ensureMonthPartitions, a safe no-op before this migration). portfolio_flow_events is partitioned separately and differently, BY HASH (wallet), by migration 072 below. See the migration header and docs/database.md.

Runbook (staging first, then prod after a soak):

bash
# 0. PAUSE THE NIGHTLY RESEED for the whole verification window (see the note below):
touch /root/.reseed-paused
# 1. Staging — apply the additive Phase C migrations (064/065/066 already; nothing new
#    additive in C), then apply 067 EXPLICITLY with --allow-destructive:
cd /opt/onchain-credit-staging && \
  scripts/ops/migrate.sh "postgresql://onchain_credit_staging@127.0.0.1:5432/creddit_staging" --allow-destructive
# 2. Verify: row counts match, the parent carries its FIVE indexes (4 + PK) and the month
#    bounds are exact UTC midnights, /portfolio spot-check, then drop the aside BY HAND:
#    psql> SELECT count(*) FROM onchain_credit.portfolio_position_snapshots;         -- new
#    psql> SELECT count(*) FROM onchain_credit.portfolio_position_snapshots_preswap; -- old (equal)
#    psql> SELECT c.relname FROM pg_class c JOIN pg_index i ON i.indexrelid = c.oid
#           WHERE i.indrelid = 'onchain_credit.portfolio_position_snapshots'::regclass;
#          -- expect: portfolio_pos_wallet_ts_idx, portfolio_pos_chain_ts_idx,
#          --         portfolio_pos_pendle_ptkey_idx, portfolio_pos_accounting_asset_idx,
#          --         portfolio_position_snapshots_pkey  (anything missing is missing FOREVER
#          --         once _preswap is dropped: migrate.sh has recorded 067)
#    psql> SELECT c.relname, pg_get_expr(c.relpartbound, c.oid) FROM pg_class c
#           JOIN pg_namespace n ON n.oid = c.relnamespace
#           WHERE n.nspname = 'onchain_credit' AND c.relname LIKE 'portfolio_position_snapshots_2%';
#          -- expect 00:00:00+00 boundaries; anything else means the month arithmetic and the
#          -- runtime helper's UTC literals disagree and will collide at the next rollover
#    psql> DROP TABLE onchain_credit.portfolio_position_snapshots_preswap;
# 3. Prod (gated on Fred's approval; run while the spine is near-empty):
cd /opt/onchain-credit && \
  scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)" --allow-destructive
#    Verify + DROP _preswap by hand exactly as on staging.
# 4. Only after the _preswap table is dropped on BOTH environments, resume the reseed:
rm -f /root/.reseed-paused

Because 067 renames + swaps inside migrate.sh's single transaction, a failure rolls the whole thing back and leaves the original table untouched — it is atomic. A re-run detects the table is already partitioned and no-ops.

Why step 0 exists. RENAME carries a table's constraints, so portfolio_position_snapshots_preswap keeps migration 056's FK to accounts plus a full copy of every wallet's history. Prod backs up at 02:15 UTC and reseed-staging.sh restores that dump at 03:00, so an aside table left standing overnight rides into staging — and the scrub's single TRUNCATE then fails (cannot truncate a table referenced in a foreign key constraint), aborting the reseed before its fail-closed leak checks and leaving staging serving the unscrubbed prod database, every night, until the aside table is dropped. portfolio_position_snapshots_preswap is listed in scripts/ops/scrub-staging-pii.sql and in the reseed's leak check (to_regclass-guarded, so it is a no-op when absent), which fixes it properly; the pause is the belt-and-braces half. scripts/ops/scrub-staging.test.ts keeps the two lists in lockstep, and portfolio_flow_events_preswap was pinned alongside it pre-emptively — migration 072 now produces exactly that table, so the fix was already in place when the flow repartition landed rather than being rediscovered by a failed reseed.

Partition maintenance after 067. Runtime creation is a backstop, not the primary path: the 6h cron pre-creates the CURRENT and NEXT month's partition for the spine, so the rollover fires from a quiet non-request process rather than from whichever writer happens to produce the first row of a new month. CREATE TABLE … PARTITION OF takes ACCESS EXCLUSIVE on the parent and Postgres's lock queue is FIFO, so the DDL runs under a 2s lock_timeout — queued behind one slow reader it gives up rather than parking every later /portfolio SELECT behind itself, and the next writer retries. Nothing to do operationally.

Applying 067 under running writers. The 6h tick, the minutely drain's children and the app all cache "is this table partitioned?" per process, and every one of them answered no before you ran the migration. That answer is NOT pinned: a negative expires after 60s, so a process that started before the migration begins creating month partitions within a minute, without a restart. A 23514 no partition of relation from a write also invalidates the cache immediately, which shortens that window for the writers whose caller survives the error (a drain child moves to the next wallet in-process); the 6h tick instead ends on the throw, so there the TTL is the whole mechanism and the cost is at most one missed snapshot window. Nothing to do operationally; noted because the failure it prevents is quiet (a snapshot missing beside a live balance reads as yield).

Flow-ledger repartition: hash by wallet (migration 072) ​

  • belongs to: migration 072 (flow-ledger repartition, hash by wallet) — v0.27.0
  • executed: unverified

This procedure is spent: it targets portfolio_flow_events, which migration 095 dropped on prod on 2026-09-05 (the retirement runbook). 072 carries a -- DESTRUCTIVE tag on line 1, so the fixture build always skips it and migrate.sh skips it until a hand-run --allow-destructive — which nobody should now give it. What follows is the record of a repartition that already ran, kept for the next one: the deploy-order hazard and the pruning law are what generalise, not the steps.

What it did. 072 rebuilds onchain_credit.portfolio_flow_events as PARTITION BY HASH (wallet) with MODULUS 16 — 16 partitions (portfolio_flow_events_h00 … h15), created ONCE by the migration because a hash modulus is fixed at CREATE time. ~6,250 wallets per partition at the 100k target. It renames the live table aside to portfolio_flow_events_preswap (including its index names — same trap as 067: a table rename leaves index names behind and CREATE INDEX IF NOT EXISTS matches on name, so without that step the new parent would end up carrying nothing but its PK), builds the partitioned replacement with identical columns / PK / CHECKs / the five indexes / the 056 FK / grants, copies every row, and KEEPS _preswap for a manual DROP. Tagged -- DESTRUCTIVE, so the staging auto-apply and a plain migrate.sh SKIP it; it runs only under --allow-destructive.

⚠ DEPLOY + ROLLBACK WARNING: the order is ONE-WAY. Ship the code release first, then apply 072. That release is a rollback floor for as long as this table is hash-partitioned. The PK genuinely does not change — wallet is already the second column of (chain_id, wallet, tx_hash, log_index, leg), so the partition key is inside the unique constraint Postgres requires it in and all three writers' 5-column ON CONFLICT targets match it exactly, before and after — but that buys the forward direction only:

  • Forward (this release's code, table not yet partitioned) — FREE. The only code change in the release is the DELETION of the five ensureMonthPartitions calls naming this table — one in live.ts, one in refreshers/portfolio.ts and three in backfill.ts, all of them the flow writers of the day (every one of those writers has since been deleted outright with the old engine) — all no-ops while the table was un-partitioned, plus the helper's partstrat guard. Nothing new is referenced, so the new code is correct against the old table for as long as it takes to get to the migration.
  • Backward (the previous release's code, table already partitioned) — HARD-BROKEN. Every flow read and write is fine on its own; it names the parent, never a partition. What breaks is the vestigial DDL call in front of the write. The previous release's ensureMonthPartitions gates on relkind = 'p' alone, so 072 flipping the parent to 'p' stops those five call sites no-opping and starts them issuing CREATE TABLE … PARTITION OF <hash parent> FOR VALUES FROM (…) TO (…), which Postgres rejects: 42P16 invalid bound specification for a hash partition. It never self-heals (isMissingPartitionError requires 23514, so the self-heal path declines 42P16, and the positive relkind memo is permanent for the process lifetime; a restart re-probes and gets 'p' again). Verified end-to-end on PG 16 against the deployed helper.
  • Blast radius, loud on one half and silent on the other. This describes the ROLLBACK TARGET, i.e. the pre-072 build, whose tick committed its snapshots before the first writeFlows — so it advances balances and then throws on the flow write, the cron alert fires, and a balance standing with no flow behind it reads as yield (the M3 violation). (A current build cannot reach that half-state at all: the tick publishes both halves in one transaction, so a failing flow write rolls the snapshots back with it. The warning is about what redeploying an older build does, and that is unchanged.) live.ts writeFlowRows sits inside the JIT try whose catch only logs mini flow scan failed, so the JIT flow persist and the provisional self-clean fail with no alert on every page load. All three backfill.ts call sites are pool-side, so they throw before their transaction ever opens.

Same class as 044 (hard-coupled, though 044 was coupled in both directions); unlike 067, whose forward direction needed the helper's memo semantics. This matters operationally because the bad order is reachable without an operator decision: deploy.yml reverts the tree with git reset --hard $PREV on an npm ci / npm run build failure (a documented recurring flake here), which lands the pre-072 code on a hash parent by itself. If the accompanying deploy fails its build, roll forward (re-run the deploy) rather than leaving the tree on $PREV. This is the same rule as the general one in the runbook's migrations section: the deploy's code-rollback path does not roll back the DB.

Pick a quiet window as well: the copy is a single statement under migrate.sh's statement_timeout=300s, and the rename needs ACCESS EXCLUSIVE within lock_timeout=10s.

Runbook (staging first, then prod after a soak):

bash
# 0. PRECONDITION — the DEPLOYED code must already be the release that ships 072. The
#    previous release's flow writers call ensureMonthPartitions behind a relkind-only probe,
#    so the moment the parent becomes hash-partitioned they emit month bounds at it and
#    EVERY flow write fails 42P16 (see the warning above). Confirm the box is running the
#    right build BEFORE touching migrate.sh — the partstrat guard is the marker:
#      cd /opt/onchain-credit-staging && git log -1 --format='%h %s'
#      grep -c partstrat src/lib/portfolio/partitions.ts      # must be > 0
#      grep -c 'portfolio_flow_events' <(grep -rh 'ensureMonthPartitions(' \
#        src/lib/portfolio scripts/refreshers)                # must be 0
#    If that fails, deploy first. If a deploy build FAILED and deploy.yml reverted the tree
#    to $PREV, re-run the deploy (roll forward) — do not migrate against $PREV.
# 0a. PAUSE THE NIGHTLY RESEED for the whole verification window — same reason as 067
#     (the aside table inherits the 056 FK to accounts and breaks the scrub's TRUNCATE):
touch /root/.reseed-paused
# 0b. PRE-FLIGHT: how big is the copy? migrate.sh runs every file under
#     statement_timeout=300s and lock_timeout=10s, and the copy is ONE statement.
#     psql> SELECT count(*), pg_size_pretty(pg_total_relation_size('onchain_credit.portfolio_flow_events'))
#            FROM onchain_credit.portfolio_flow_events;
#     A few million rows copy well inside 300s; if it would not, do NOT split the migration
#     (its atomicity is the safety property) — run that one file by hand with a raised
#     timeout instead, then record it in the ledger:
#       sudo -u postgres env PGOPTIONS='-cstatement_timeout=1800s -clock_timeout=10s' \
#         psql -v ON_ERROR_STOP=1 -X -q -1 -d <db> -f scripts/sql/072-repartition-portfolio-flows.sql
#       sudo -u postgres psql -q -d <db> -c "INSERT INTO onchain_credit.schema_migrations(filename) \
#         VALUES ('072-repartition-portfolio-flows.sql')"
# 1. Staging — 072 is DESTRUCTIVE, so it needs the explicit flag:
cd /opt/onchain-credit-staging && \
  scripts/ops/migrate.sh "postgresql://onchain_credit_staging@127.0.0.1:5432/creddit_staging" --allow-destructive
# 2. Verify — counts, the 16 partitions, the SIX indexes (5 + PK), and an EXPLAIN prune:
#    psql> SELECT count(*) FROM onchain_credit.portfolio_flow_events;         -- new
#    psql> SELECT count(*) FROM onchain_credit.portfolio_flow_events_preswap; -- old (equal)
#    psql> SELECT count(*) FROM pg_class c JOIN pg_inherits i ON i.inhrelid = c.oid
#           WHERE i.inhparent = 'onchain_credit.portfolio_flow_events'::regclass;   -- expect 16
#          -- 072 now ASSERTS this itself (16 partitions, 16 distinct remainders, before the
#          -- copy, so a shortfall aborts the atomic file). This query is the belt-and-braces
#          -- half: the case it guards is a relation already occupying one of the
#          -- portfolio_flow_events_hNN names, which `CREATE TABLE IF NOT EXISTS ...
#          -- PARTITION OF` matches on NAME and would otherwise adopt-around silently.
#    psql> SELECT c.relname FROM pg_class c JOIN pg_index i ON i.indexrelid = c.oid
#           WHERE i.indrelid = 'onchain_credit.portfolio_flow_events'::regclass;
#          -- expect: portfolio_flow_wallet_block_idx, portfolio_flow_wallet_pos_idx,
#          --         portfolio_flow_asset_idx, portfolio_flow_pendle_ptkey_idx,
#          --         portfolio_flow_provisional_idx, portfolio_flow_events_pkey
#          --         (anything missing is missing FOREVER once _preswap is dropped:
#          --          migrate.sh has recorded 072, so it never re-runs to reconcile)
#    psql> EXPLAIN (COSTS OFF) SELECT tx_hash, log_index FROM onchain_credit.portfolio_flow_events
#           WHERE chain_id = 1 AND wallet = '<a real lower-cased wallet>'
#           ORDER BY block_number DESC, log_index DESC;
#          -- expect ONE partition in the plan (e.g. ..._h06) and NO Append node. An Append
#          -- over all 16 means the wallet predicate is not pruning and the repartition has
#          -- bought nothing.
#    psql> ANALYZE onchain_credit.portfolio_flow_events;   -- fresh stats on the new relations
#    then a /portfolio + /portfolio events spot-check on a whale fixture wallet.
#    psql> DROP TABLE onchain_credit.portfolio_flow_events_preswap;
# 3. Prod (gated on Fred's approval; quiet window). RE-CHECK step 0's precondition here:
#    prod migrations are a separate manual step from the prod deploy, so this is the one
#    place the wrong order is easy to reach by hand.
cd /opt/onchain-credit && \
  scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)" --allow-destructive
#    Verify + ANALYZE + DROP _preswap by hand exactly as on staging.
# 4. Only after _preswap is dropped on BOTH environments, resume the reseed:
rm -f /root/.reseed-paused

Because 072 renames + creates + copies inside migrate.sh's single transaction, a failure anywhere rolls the whole thing back and leaves the original table untouched — it is atomic. A re-run detects the table is already partitioned and no-ops.

Why step 0a exists is exactly the 067 story: RENAME carries a table's constraints, so portfolio_flow_events_preswap keeps migration 056's FK to accounts plus a full copy of every wallet's flow history. Prod backs up at 02:15 UTC and reseed-staging.sh restores that dump at 03:00, so an aside table left standing overnight rides into staging and the scrub's single TRUNCATE then fails, aborting the reseed before its fail-closed leak checks. portfolio_flow_events_preswap was added to scripts/ops/scrub-staging-pii.sql and the reseed leak check pre-emptively (both to_regclass-guarded), so the mechanism is already in place and scripts/ops/scrub-staging.test.ts now checks both ends of the contract against 072 itself. The pause is the belt-and-braces half.

Partition maintenance after 072: there is none. All 16 partitions exist by construction, so unlike the snapshot spine there is no month rollover, no runtime DDL, no ACCESS EXCLUSIVE parent lock on a write path, and no reason to hand the parent to the app role — it stays owned by postgres with the app holding DML grants only (the 16 partitions pick up the schema's ALTER DEFAULT PRIVILEGES grant at CREATE time, but nothing depends on that: privileges are checked on the relation a query names, and tuple routing does not re-check them). The writers' partition calls for this table are deleted, and three layers keep them gone: ensureMonthPartitions' table parameter no longer ADMITS the flow ledger (MonthPartitionedTable excludes it, so the copy-paste does not compile), the helper refuses any non-RANGE parent at runtime (it probes pg_partitioned_table.partstrat), and a source tripwire in src/lib/portfolio/partitions.test.ts catches a literal call. Without those, month bounds against a hash parent are rejected outright (invalid bound specification for a hash partition) — which is the whole reason the deploy order above is one-way.

If the 16 partitions ever need to become 32 (they will not at the 100k target): 16 is a power of two, and Postgres allows mixed moduli as long as each divides the next, so it is an incremental DETACH of one MODULUS 16 partition plus ATTACH of two MODULUS 32 partitions with remainders r and r+16, one at a time — not another full rebuild.

Flow basis provisional (migration 070, additive). Widens the portfolio_flow_events.basis CHECK to admit provisional and adds the partial index the two provisional deletes use (see database.md). Staging auto-applies it on deploy; prod is the usual gated manual migrate.sh run. Apply it BEFORE the code restart — not "before or with", and never after: until the constraint is widened, the JIT's flow persist fails on any flow landing in the last ~64 blocks (the whole persist transaction rolls back and the JIT logs mini flow scan failed). Nothing is corrupted (a rejected insert writes nothing) and the flow is not lost, but two details make the window worse than it looks and neither is self-announcing:

  • It does not heal on the next refresh. Every subsequent JIT refresh of that wallet fails on the same CHECK for as long as the flow sits in the reorg-exposed tail; only the next 6h cron tick — which writes live rows exclusively and so never touches the widened value — actually lands it. Up to 6h of "my deposit is not showing".
  • Nothing pages you. The failure is caught by the JIT and written with console.error to the app's pm2 log, not to run-cron.sh's log, and the cron alert needs a non-zero exit and a matching line. JIT flow persistence can be dead for hours in silence, so grep pm2 logs for mini flow scan failed if you ever run the code ahead of 070.

The cron's settle sweep is cheap without the index (it is bounded by the tick's wallet list and block window, so it can fall back to portfolio_flow_wallet_block_idx), but it runs once per tick against the whole flow ledger — one more reason not to leave the window open. Rollback-safe in the other direction: the previous release only ever writes live/backfill, which the widened CHECK still admits.

Migration 079 (exposure key gains the collateral address, additive) ​

  • belongs to: migration 079 (exposure key gains the collateral address) — v0.36.0
  • executed: unverified

Widens market_collateral_exposure's primary key with collateral_address, so two isolated markets on one deposit asset whose collateral shares a ticker are two rows instead of one contested key (database.md). Additive and idempotent, and the new key is a SUPERSET of the old one, so uniqueness only relaxes and no stored row moves: staging auto-applies it on deploy and prod is the usual gated manual migrate.sh run after the release.

No special ordering, unlike 044 / 070 / 072. The deploy ships code only and a prod migration is a manual step after it, so code-then-migration is the default order here, and for this file that order is the benign one. In that window a live ticker pair has the first market's INSERT commit and the second violate the still-narrow key; the second rolls back alone with a [morpho/fail] line, so one market publishes a fresh row and the other keeps its previous snapshot (before this release the writer withheld both). Which of the two publishes follows the registry read's row order, so it can differ between runs while the window is open; nothing is mislabelled, because every row carries its own collateral address. Run migrate.sh after the deploy and the next 6h refresh-assets.ts tick closes it. Rollback-safe in the other direction: the previous release's three writers bind exactly these columns and only produce rows the wider key still accepts.

The nightly reseed reverts it on staging. ops/reseed-staging.sh restores prod's schema and its schema_migrations ledger (§3.2), so until 079 is applied on PROD every 03:00 reseed drops it from staging and the next migrate.sh reports 0 pending. A next-morning validation pass would then run against the pre-079 schema, where the ticker-twin behaviour is simply absent rather than broken. Pause the reseed for a multi-day validation window (touch /root/.reseed-paused) or re-run the staging deploy before checking.

Migrations 082 / 083 (flow ledger + registries, additive) ​

  • belongs to: migrations 082 / 083 (flow ledger + registries) — v0.42.0
  • executed: unverified

082 creates the flow ledger portfolio_flow_events_v2 (empty), the chain-identity tables, the impairment record and the two registries; 083 seeds the registries (database.md). The release carrying them changes no application code, so nothing reads any of it and no served number can move. Both are additive: staging auto-applies them on deploy, prod is the usual gated manual migrate.sh run.

Quiesce before the prod run, including the ingester. 082 swaps a CHECK on raw_events, which takes ACCESS EXCLUSIVE on the parent and all 23 partitions for the duration of the catalogue update, while creddit-event-ingester writes that table on a ~60s loop and migrate.sh runs under lock_timeout = 10s. Failure is safe (the file rolls back whole under psql -1) but a runbook should not discover its own lock contention. In order: drain the backfill queue, comment out the five prod portfolio crontab lines (drain-portfolio-backfills.ts, refresh-portfolio.ts, refresh-portfolio-discovery.ts, refresh-portfolio-reconcile.ts, sync-portfolio-tokens.ts — one root crontab holds prod and staging, separated only by the /opt/onchain-credit vs /opt/onchain-credit-staging path prefix, so read the prefix on every line), then pm2 stop creddit-event-ingester. Restore all five lines and pm2 start creddit-event-ingester in the same window, before anything else begins. A release deploy inside the window leaves the stopped ingester stopped (the deploy's restart script skips a stopped process), and the hourly freshness alarm pages until it is started again.

That list is the complete set of writers. The app stays up and is a reader of both altered tables (raw_events on the JIT ledger path, portfolio_position_snapshots on every /portfolio render), so if the run dies on lock_timeout the likely holder is a page load, not a cron: retry, or stop onchain-credit for the window too. While the migration holds the lock, page loads block until it commits, which is seconds.

bash
cd /opt/onchain-credit
scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)"

Never hand-run psql -f scripts/sql/082-*.sql. It bypasses schema_migrations, so the ledger still reports the file pending and the next migrate.sh re-applies it. If a file genuinely must be hand-run, its INSERT INTO onchain_credit.schema_migrations(filename) VALUES (...) is part of the same procedure, not an afterthought.

Verification, after the run:

sql
-- 16 partitions, 16 distinct remainders, and the FK the user wipe depends on
SELECT count(*), count(DISTINCT pg_get_expr(c.relpartbound, c.oid))
  FROM pg_class c JOIN pg_inherits i ON i.inhrelid = c.oid
 WHERE i.inhparent = 'onchain_credit.portfolio_flow_events_v2'::regclass;   -- 16 | 16
\d onchain_credit.portfolio_flow_events_v2                                  -- pfe2_wallet_fk

-- The widened raw_events CHECK. Read the DEFINITION first, then the flag.
SELECT conname, convalidated, pg_get_constraintdef(oid) FROM pg_constraint
 WHERE conrelid = 'onchain_credit.raw_events'::regclass;
-- raw_events_stream_chk must list 'wallet-token'. If it does not, the DROP/ADD above did
-- not run and this is 064's narrow six-name constraint under the same name: stop.
-- With 'wallet-token' present, BOTH readings of convalidated can be correct, and which one
-- to expect is decided by a fact you can check on the box rather than by anything in this
-- query -- is scripts/sql/084-raw-events-stream-validate.sql part of THIS release?
--   * absent (082 shipping alone)      -> FALSE. The VALIDATE is a later release's file.
--   * present (082 and 084 together)   -> TRUE, and that is the fully correct end state:
--     one migrate.sh invocation applies every pending file, so a release carrying both
--     applies both. Confirm `APPLY: 084-raw-events-stream-validate.sql` in the run's
--     output and finish at 084's own acceptance query below, which reads the parent AND
--     every partition. Do not stop.
-- TRUE with the file ABSENT from the release is the one bad reading here: something
-- validated this constraint outside the runner. Stop.

-- Both snapshot CHECKs widened (under _chk2 on the servers), and the seeds present
SELECT conname, pg_get_constraintdef(oid) FROM pg_constraint
 WHERE conrelid = 'onchain_credit.portfolio_position_snapshots'::regclass
   AND conname ~ '(venue|basis)';                       -- must list 'escrow' / 'provisional'
SELECT count(*) FROM onchain_credit.reward_distributors;             -- 4
-- ORDER BY, so the expected triple below is read against a fixed order rather than
-- against whatever order the grouping happens to return:
SELECT kind, count(*) FROM onchain_credit.token_lineage GROUP BY 1 ORDER BY 1;
-- address_migration 2 | rebook 4 | wrapper_rotation 4

Where the other half went, and why this step reads a file listing before it reads a flag. The VALIDATE that flips raw_events_stream_chk to convalidated = true is its own file, Migration 084, which is also where the constraint's acceptance query lives. 082 was written expecting to reach prod one release ahead of it, and false is the correct reading in that case. But migrate.sh has no per-file selector and a release PR's diff is everything on staging, so whether the two files reach prod in one invocation or two is decided by merge order on staging, months before anyone reads this step, and it is not a thing the operator at the keyboard can verify. The presence of the file in the release is, so that is what the step keys on. Both orderings are supported; neither is a defect; the only bad reading is convalidated = true with no 084 in the release.

If 082's parent-level ADD … NOT VALID ever falls back to per-partition statements, the parent is part of the procedure. The file's header offers DROP / ADD … NOT VALID per partition should a future environment refuse the parent-level form. Two things about that fallback, both measured on PG 16.14: the partitions' copies are inherited, so ALTER TABLE onchain_credit.raw_events_p90 DROP CONSTRAINT raw_events_stream_chk fails outright (cannot drop inherited constraint) while the parent still carries 064's — the fallback is not applicable one partition at a time on its own. And if it is reached the long way round, by dropping on the parent first, the widened constraint has to be re-added on the parent as well: a parent left on 064's six-name CHECK rejects the first wallet-token row with 23514, and a name-only acceptance query reports that state as green. This is the same "stop before the parent" defect that 084's own fallback carries a correction for, and it is why 084's acceptance query matches the constraint's definition rather than its name.

The nightly staging reseed is part of this migration's blast radius, and the fix ships with it. portfolio_flow_events_v2 carries an FK to accounts, and the scrub truncates the whole user-data graph in ONE statement; a table missing from that statement makes the TRUNCATE fail, which aborts reseed-staging.sh under set -euo pipefail before every leak check below it and leaves staging serving an unscrubbed copy of the prod user-data graph. scripts/ops/scrub-staging-pii.sql, the reseed's leak check, scripts/ops/scrub-staging.test.ts and scripts/ops/reset-portfolio-users.ts are all updated in the same release. After 082 reaches prod, watch the first 03:00 reseed: it must exit 0.

Staging only: give the staging role runtime partition auto-create on raw_events, and again after every reseed. It takes BOTH statements.

bash
sudo -u postgres psql -d creddit_staging \
  -c "ALTER TABLE onchain_credit.raw_events OWNER TO onchain_credit_staging" \
  -c "GRANT CREATE ON SCHEMA onchain_credit TO onchain_credit_staging"

Staging connects as onchain_credit_staging, which neither owns the partitioned parent nor holds the schema CREATE grant, so runtime partition auto-create fails there. ensurePartitions issues CREATE TABLE IF NOT EXISTS onchain_credit.raw_events_pNN PARTITION OF …, and that one statement needs both privileges: ownership of the parent (or it fails must be owner of table raw_events) and CREATE on the schema (or it fails permission denied for schema onchain_credit). Owning the parent is necessary but not sufficient — 064's own header says so, which is why 064 also granted the prod role CREATE ON SCHEMA onchain_credit. Measured on a PG 16.14 scratch cluster reproducing staging's exact ACL ({postgres=UC/postgres,onchain_credit=UC/postgres,onchain_credit_staging=U/postgres}): the ALTER alone still fails permission denied for schema onchain_credit; the GRANT alone still fails must be owner of table raw_events; both together succeed. Note that ALTER TABLE … OWNER TO does not recurse to existing partitions, and does not need to: DML on those is covered by the reseed's GRANT … ON ALL TABLES, and only the parent's owner matters for creating a new one.

Both statements repeat after every reseed, for the same reason: reseed-staging.sh restores the prod dump with --no-owner (so the tables come back owned by postgres) and re-grants the staging role USAGE on the schema plus DML on all tables — never CREATE, and never ownership. A manual step repeated after every reseed is a step that will eventually be skipped, so the durable fix is to move both statements into the reseed's grant block, next to the GRANT USAGE. That is deliberately not done in this release: it hands the staging app role standing DDL rights on the schema, which is a call to make on purpose rather than as a side effect of a runbook edit, and nothing needs the privilege until the band is exhausted (below).

Do not read "no failure yet" as evidence this worked, and do not expect a failure yet either. Two measured facts combine here. First, the whole materialised band already exists: prod and staging each carry 23 raw_events partitions spanning p90[22,500,000, 22,750,000) through p112 [28,000,000, 28,250,000), because the one-time 064 backfill auto-created p90–p97 under the prod role and staging inherits the whole set from the dump. The rebuild's 22,527,558 history floor therefore lands in an existing partition. Second, CREATE TABLE IF NOT EXISTS … PARTITION OF checks the schema privilege before the "already exists, skipping" shortcut, so on staging today that statement raises permission denied for schema onchain_credit even for a partition that is already there [measured on PG 16.14] — and ensurePartitions catches it, re-checks existence with to_regclass, finds the partition present, and continues. So the current staging symptom is a swallowed error plus an existence probe per partition index, not a broken scan. The loud failure (ensurePartitions rethrows when the partition really is absent) arrives at the first index that does not exist, i.e. once the head crosses 28,250,000, ~2.4M blocks out. The step is cheap and belongs in the reseed routine precisely because the day it is needed is the day nothing else warns you. Verify it directly rather than by absence of an error:

sql
SELECT pg_get_userbyid(relowner)                                        -- onchain_credit_staging
  FROM pg_class WHERE oid = 'onchain_credit.raw_events'::regclass;
SELECT has_schema_privilege('onchain_credit_staging','onchain_credit','CREATE');   -- t

portfolio_flow_events_v2 needs no equivalent: it is hash-partitioned with all 16 partitions created up front by 082, so it has no runtime auto-create path at all.

Staging only: a nightly reseed REMOVES 082's objects until the next deploy.reseed-staging.sh restores staging from a prod dump and does not run migrate.sh (schema_migrations comes from the dump as well), while the staging deploy does run the runner. So in the window between merging this PR and 082 reaching prod, each 03:00 reseed drops the flow ledger, the chain-identity tables and the registries from staging, and the next staging deploy re-applies 082 and 083. Two consequences, both about not misreading staging in that window: (a) checking the 16 partitions or the seed counts on staging on a later morning finds them absent, and that is the reseed rather than a failed migration (re-deploy staging, or touch /root/.reseed-paused across a validation window, before reading anything into it); (b) a reseed that exits 0 in that window is not evidence the scrub fix works, because the table the scrub entry was added for is not in the dump yet. That is why the blast-radius note above waits for the first 03:00 reseed after 082 reaches prod.

Rollback: none needed. Both files are additive and unread; reverting the release's code leaves the tables in place, which is the expand half of expand/contract.

Migration 084 (the raw_events stream CHECK validation) ​

  • belongs to: migration 084 (the raw_events stream CHECK validation) — v0.42.0
  • executed: unverified

A later release than 082, deliberately, and the file is only on the box from that release onward. 082 widened raw_events' stream CHECK as DROP + ADD … NOT VALID, which is a catalogue update: the constraint rejects a bad stream name on every new row immediately, but reads convalidated = false because nothing has scanned the 7.8M stored rows yet. 084 is the matching VALIDATE CONSTRAINT, and it is one statement.

It is a separate release, not just a separate file, because migrate.sh has no per-file selector: one invocation applies every pending file in ls | sort order, so "apply 082, verify, then 084" is not expressible inside one release. Selection is by presence on disk. Had 084 shipped in 082's release, the same invocation would have applied it and 082's own acceptance query (convalidated = false) would have been false as written.

If the two do arrive together, nothing here breaks — only the intermediate reading disappears. Which release each file lands in is set by merge order on staging, so a prod release can carry 082, 083 and 084 at once. One invocation then applies all three, in ls | sort order, and prod goes straight to the end state: 082's step reads convalidated = true (correct, and its runbook entry says so), the "expected state before this file" below is never observable on prod, and this section's verification query is the one that decides whether the release is good. The quiesce below is 082's quiesce in that case, which is the stricter of the two, so follow that one.

bash
cd /opt/onchain-credit
scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)"

Quiesce is the same shape as 082's, and for a weaker reason. VALIDATE CONSTRAINT takes SHARE UPDATE EXCLUSIVE, which blocks neither reads nor writes on raw_events, so the ingester can keep running; what it does conflict with is another SHARE UPDATE EXCLUSIVE holder, i.e. a concurrent VACUUM or ALTER. With lock_timeout = 10s that is a failed acquisition, not an outage, and the fix is to retry.

Budget the scan, which is smaller than the table. VALIDATE CONSTRAINT reads the heap, and raw_events is 3,908 MB of heap inside 8,313 MB of total relation size — the difference is the indexes, which this statement does not touch [measured read-only on prod, 2026-08-18]. For scale: a full heap read of staging's copy of the same table (7,782,149 rows) returns in 1.4 s warm, so the statement_timeout = 300s is not a tight budget and a 57014 here means something is wrong rather than that the table is merely large. If it does time out, re-run migrate.sh — the file rolls back whole under psql -1, so a re-run is clean. If it times out twice, apply the same VALIDATE per partition, 23 statements, one at a time (each scan a 23rd of the table), and then run the parent statement once:

sql
ALTER TABLE onchain_credit.raw_events_p90 VALIDATE CONSTRAINT raw_events_stream_chk;
-- … p91 … p112, one statement at a time …
ALTER TABLE onchain_credit.raw_events     VALIDATE CONSTRAINT raw_events_stream_chk;  -- required

The last line is not a repeat of the 23 above it. Validating the partitions flips convalidated on the partitions only and leaves the parent row at false, which is the row the acceptance query reads, so a fallback that stops at the 23rd statement finishes with a red check and the constraint still unusable [measured on PG 16.14, three-partition replica, 3.1M rows]. With every partition already validated the parent statement does not re-scan: 1.3 ms against 945 ms for the full parent scan on that same replica. The lock profile is the same either way.

On staging, "once" means once per deploy until 084 reaches prod. The reseed interaction described for 082 above applies here too: each 03:00 reseed restores staging from a prod dump, schema_migrations included, so 082–084 disappear and the next staging deploy re-applies all three — meaning the full validation scan re-runs on every staging deploy in that window, not once. It stays inside the 300s budget, and reseed-staging.sh's own database-wide ANALYZE takes the same SHARE UPDATE EXCLUSIVE this section warns about, so a deploy landing during the reseed can fail its lock acquisition (55P03) and simply needs re-running.

It cannot fail on stored rows. The widened value set is a strict superset of the one the old CHECK validated, so every stored row already satisfies it. A 23514 here would mean something wrote a stream name outside both lists, and the response is to find that writer, not to widen the CHECK again.

Verification, after the run — this is the check 082's step deliberately expected false from. It reads the parent and every partition, because the per-partition fallback above is the one procedure that can leave the two disagreeing, and a partial validation must not read as success in either direction:

sql
SELECT count(*) AS relations,
       count(*) FILTER (WHERE NOT c.convalidated) AS not_validated
  FROM pg_constraint c
 WHERE c.conname = 'raw_events_stream_chk'
   AND pg_get_constraintdef(c.oid) LIKE '%wallet-token%'
   AND (c.conrelid = 'onchain_credit.raw_events'::regclass
        OR c.conrelid IN (SELECT inhrelid FROM pg_inherits
                           WHERE inhparent = 'onchain_credit.raw_events'::regclass));
-- 24 | 0   (the parent plus its 23 partitions, none left NOT VALID)

The wallet-token clause is what makes the reading mean anything, and relations is half the check. raw_events_stream_chk is 064's constraint name as much as 082's: 064 created it with the original six stream names, so a database that never ran 082 carries a constraint of exactly that name, already validated. Matched on the name alone this query returns 24 | 0 there — the success reading — on a database that admits none of the seven new streams, and 084 itself does not fail on such a box either: it re-validates 064's narrow constraint and returns. Both measured read-only on prod, 2026-08-18, with schema_migrations topping out at 081. With the definition clause the same box reads 0 | 0, and staging (where 082 is applied) reads 24 | 24 before the run. So read both numbers: relations = 0 means the widened constraint is absent, i.e. 082 has not run, and not_validated = 0 on its own certifies nothing.

24 is the box's partition census plus one, not a constant: 23 partitions on prod and staging today, 15 on a from-scratch fixture (16 | 0 there). Swap the aggregate for SELECT c.conrelid::regclass, c.convalidated … ORDER BY 1 to see which relation is lagging when not_validated is not 0. Match through pg_inherits rather than a name pattern: regclass renders unqualified when the schema is on search_path, so a LIKE 'onchain_credit.raw_events%' silently matches nothing on a session that has it there.

The reachable way to be shown a false green is the staging reseed window, not a mis-ordered runner: each 03:00 restore takes staging's schema_migrations back below 082 and restores 064's constraint with it, so a name-only query run on staging on a later morning reports 24 | 0 while none of the release's schema is present. The definition clause makes that state read as 0 | 0.

Rollback: none needed. Validating a constraint changes no row and no application behaviour; reverting the release's code leaves it validated.

Money market funds: first deploy (migration 086) ​

  • belongs to: migration 086 (money market funds) — v0.44.0
  • executed: unverified

/money-market-funds needs migration 086 plus one seeding run before the tab shows anything. Everything below is safe to run against staging; nothing here touches production without an explicit decision.

The page is prerendered, so its queries run during the BUILD that precedes the migration. Its reader probes information_schema first and renders an empty tab loudly rather than failing the deploy, which is what makes the pre-migration build safe. Keep that probe until 086 is on prod AND a prod dump has been reseeded to staging, because the nightly reseed rebuilds creddit_staging from the prod dump and would otherwise take the tables away every night.

Before the deploy: check the ledger does not already carry 086. The migration runner keys on FILENAME alone, with no checksum, and this file gained columns during review. Any database that ran an earlier copy of it gets SKIP and never receives them, while the reader names them all. On a database that already has the row, apply the ALTER TABLE ... ADD COLUMN IF NOT EXISTS block at the foot of scripts/sql/086-money-market-funds.sql by hand; it is a no-op where the columns exist.

sql
SELECT filename FROM onchain_credit.schema_migrations
 WHERE filename = '086-money-market-funds.sql';   -- expect NO row before the deploy
bash
# 1. Confirm the migration applied. A SKIP looks exactly like success in the log,
#    so check the ledger, not the deploy output.
sudo -u postgres psql -d creddit_staging -c \
  "SELECT filename, applied_at FROM onchain_credit.schema_migrations \
    WHERE filename = '086-money-market-funds.sql';"

# 2. Seed the registry: discover, confirm on chain, classify, propose.
#    Measured 13s against mainnet (928 vaults discovered, 116 chain-confirmed).
cd /opt/onchain-credit-staging
scripts/run-cron.sh sync-money-market-funds.ts --dry-run   # read the report first
scripts/run-cron.sh sync-money-market-funds.ts             # persist

sudo -u postgres psql -d creddit_staging -c \
  "SELECT status, count(*), round(sum(tvl_usd)/1e6) AS tvl_musd \
     FROM onchain_credit.money_market_fund_registry GROUP BY 1 ORDER BY 2 DESC;"
# Expected shape as of 2026-08-21: ~40 listed, ~37 proposed, the rest ineligible.
# The report prints an OFF PAR block (the two Metronome funds sit in it today)
# and a PAR UNMEASURED block (funds listed with the flag, none today).

# 3. First state and allocation read. Measured 23s for the ~40 listed funds.
scripts/run-cron.sh refresh-assets.ts
sudo -u postgres psql -d creddit_staging -c \
  "SELECT count(*) FILTER (WHERE withdrawable_now IS NOT NULL) AS with_exit, \
          count(*) AS total FROM onchain_credit.money_market_fund_state;"
sudo -u postgres psql -d creddit_staging -c \
  "SELECT count(*), count(DISTINCT fund_address) \
     FROM onchain_credit.money_market_fund_allocation;"

# The invariant that matters: no fund may report more exit liquidity than it has.
sudo -u postgres psql -d creddit_staging -c \
  "SELECT r.name, s.withdrawable_now, s.total_assets \
     FROM onchain_credit.money_market_fund_state s \
     JOIN onchain_credit.money_market_fund_registry r USING (chain_id, address) \
    WHERE s.withdrawable_now > s.total_assets * 1.0001;"   -- expect zero rows

# And the cross-check against Morpho's own published figure. A HANDFUL IS
# NORMAL: our figure is read at a pinned block and theirs seconds later, so a
# few funds land outside the 2% tolerance on any given tick and clear on the
# next. It is a log line for a human, never a gate. What is worth looking at is
# the SAME fund appearing tick after tick, or a sudden jump to most of the list.
sudo -u postgres psql -d creddit_staging -c \
  "SELECT count(*) FROM onchain_credit.money_market_fund_state \
    WHERE chain_api_delta IS NOT NULL;"   -- 0 to ~5 of 40 is a settled tick

# 4. Return history for the newly listed funds. LONG: budget 6-9 hours.
#    Resumable: a point already on record is KEPT, never rewritten, so an
#    interrupted run is re-run with the same command. token_yield_apy is also
#    what the portfolio values yield-token holdings from, which is why replacing
#    a covered window needs the explicit --overwrite and is not a rerun.
nohup scripts/run-cron.sh backfill-money-market-funds.ts 365 \
  >/dev/null 2>&1 &
tail -f /tmp/onchain-credit-cron/onchain-credit-backfill-money-market-funds.log

sudo -u postgres psql -d creddit_staging -c \
  "SELECT count(*) FILTER (WHERE y.a IS NOT NULL) AS with_history, count(*) AS listed \
     FROM onchain_credit.money_market_fund_registry r \
     LEFT JOIN (SELECT DISTINCT lower(token_address) a FROM onchain_credit.token_yield_apy) y \
            ON y.a = r.address \
    WHERE r.status = 'listed';"
# Target: with_history = listed.

# 5. One more tick, to confirm the share-rate snapshotter picked the new funds up
#    and did NOT push itself over the partial-failure floor.
scripts/run-cron.sh refresh-assets.ts
grep -E '\[ok\]|\[partial\]|\[fail\]' \
  /tmp/onchain-credit-cron/onchain-credit-refresh-assets.log | tail -20
# `[partial] token-yields` here is a BLOCKER, not a warning. That job carries five
# permanent failures which are held OUTSIDE its ratio (knownPermanent: 5, floor
# 3%, in refresh-assets.ts) precisely because the fund set roughly doubles its
# item count: inside a bare 10% ratio the same floor would have quietly tolerated
# eight new silent failures instead of about three.

# 6. Bad debt is read by MARKET ID, from the ids the previous tick recorded, so
#    the column is null on the first state read and populated on the second.
sudo -u postgres psql -d creddit_staging -c \
  "SELECT count(*) FILTER (WHERE bad_debt_usd IS NULL) AS unmeasured, \
          count(*) FILTER (WHERE bad_debt_usd > 0) AS carrying, count(*) AS rows \
     FROM onchain_credit.money_market_fund_allocation WHERE slot_kind = 'market';"
# After the SECOND refresh-assets.ts, `unmeasured` should be near zero. A run that
# could not reach the API logs "market bad debt unreadable this tick" and leaves
# every row null, which renders as no reading rather than as a clean bill.

# 7. Add the daily discovery cron, after the existing 3am block:
#    50 3 * * * /opt/onchain-credit-staging/scripts/run-cron.sh sync-money-market-funds.ts

The approvals are a human's. After step 2 the report's NEEDS A DECISION block lists the managers behind every proposal, collapsed one line per house, plus the funds with no readable manager (UNNAMED) and the funds whose manager was read off their own name (BY NAME). Nothing lists until someone runs --approve-manager <key>, and a BY NAME fund needs its own --bind-manager <slug> <key> on top, because a vault name is a string its deployer chose. That is the point; do not pre-approve.

A run that could not see the whole universe removes nothing. If step 2 prints INCOMPLETE DISCOVERY, the Morpho endpoint was degraded, not the fund set: the registry keeps everything it had and no vault is marked gone. Re-run it later rather than working around it.

Rollback. The migration is additive, so a code rollback needs no database change: the four tables sit unread. If the page itself has to go, revert the merge and redeploy; the tables stay and the next deploy picks them back up. Do not drop them.

Fluid per-vault rates: first deploy (migration 093) ​

  • belongs to: migration 093 (Fluid per-vault rates) — v0.55.0
  • executed: unverified

/carries prices every Fluid funding leg off fluid_vault_rates from this release on (issue #769). The table is additive and the readers withhold a snapshot they have no vault row for — never a fallback to the Liquidity-Layer token rate, never a zero — so between the deploy and the backfill a Fluid carry would show no funding figure at all. That is the whole reason this runbook orders the passes the way it does.

Prod, in this order. Steps 1 to 3 run BEFORE the merge, and that ordering is the point: the backfill needs nothing but DATABASE_URL and an archive RPC, so the first pass can run from the release branch's own script while the deployed build is still the previous release. Do it after the merge instead and every Fluid carry renders with no figures and no expansion for the deploy plus ~20 minutes.

bash
# 1. Take the migration, the backfill script and the resolver-era helper it
#    imports from the release branch WITHOUT deploying them. `staging`, not
#    `main`: the release PR has not been merged yet at this point, so main
#    carries none of the three.
#
#    The SQL file has to be fetched for the same reason the script does, and
#    that is why this step comes FIRST. `migrate.sh` applies the files present
#    in the checkout it is RUN FROM (`SQL_DIR="$(dirname "$0")/../sql"`), and
#    that checkout is the PREVIOUS release, whose highest file is 092. Run the
#    runner before this step and it prints `0 applied` and creates nothing.
#
#    pm2 serves the built .next bundle, so a source file is inert until the next
#    build, and step 4's deploy does `git reset --hard` over all three.
cd /opt/onchain-credit
git fetch "https://x-access-token:$GH_TOKEN@github.com/FredCoen/onchain-credit.git" staging
git checkout FETCH_HEAD -- scripts/sql/093-fluid-vault-rates.sql \
  scripts/refreshers/fluid-vault-rates.ts src/lib/portfolio/fluid-abi.ts

# 2. Apply the migration (additive; gated manual step on prod), then CHECK THE
#    LEDGER. Prod's deploy workflow never runs `migrate.sh` at all, so this run
#    is the only thing that ever creates the table — and a no-op run prints
#    `0 applied` and reads exactly like success.
sudo -u postgres psql -d creddit -c \
  "SELECT filename, applied_at FROM onchain_credit.schema_migrations \
    WHERE filename = '093-fluid-vault-rates.sql';"     # expect NO row first
scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)"
#    expect a `APPLY: 093-fluid-vault-rates.sql` line in that output
sudo -u postgres psql -d creddit -c \
  "SELECT filename, applied_at FROM onchain_credit.schema_migrations \
    WHERE filename = '093-fluid-vault-rates.sql';"     # expect ONE row now

# 3. FIRST PASS — the last 35 days, which is everything the screener's trailing
#    windows read. ~20 min for 21 vaults (2 archive reads per vault per 6h
#    window, one block-pair lookup per window). Run BEFORE the merge, so the
#    release builds against a table that already has the windows it reads.
scripts/run-cron.sh refreshers/fluid-vault-rates.ts --backfill \
  --from "$(date -u -d '35 days ago' +%Y-%m-%d)"

# 4. Merge the release, let the deploy finish.

# 5. SECOND PASS — the rest of the Fluid carry history depth (2025-05-21), so
#    the charts' long timeframes keep the range they have today. Idempotent, so
#    the overlap with pass 1 is harmless. Several hours; run it in tmux.
scripts/run-cron.sh refreshers/fluid-vault-rates.ts --backfill \
  --from 2025-05-21 --to "$(date -u -d '34 days ago' +%Y-%m-%d)"

# 6. Re-deploy (empty commit) so the prerendered /carries picks the long history
#    up immediately instead of at its next revalidate. See the ISR note below.

What a skipped step 2 looks like at step 3. Every write in the backfill opens with the 24h-anchor SELECT, so with no table each vault throws 42P01, is caught per vault, and the pass ends 0 written, N failed with a non-zero exit after the full ~20 minutes of archive reads. Read that as the table, not as a rate-limited RPC: re-run step 2 and check the ledger row before repeating the pass.

If the migration has NOT been applied when the deploy runs, the build no longer fails: apy.ts probes information_schema for the table once and, when it is absent, every Fluid carry withholds instead of throwing 42P01. That matters because a build precedes migrate.sh wherever the deploy runs it at all (deploy-staging.yml), so a hard failure there would roll the deploy back with the migration still unapplied and the next deploy would fail identically (the trap hit in PR #382). On prod the deploy runs migrate.sh nowhere, so the table arrives only through step 2 above and nothing downstream repairs a missed one: the degrade is a page with dashes on all 21 Fluid rows and no expansion, held until a human applies it. That is a page with no figures rather than wrong ones, and the ordering above is what avoids seeing it at all. Staging re-arms this nightly: reseed-staging.sh rebuilds creddit_staging from the prod dump, so a hand-applied 093 on staging is undone every night until 093 is on prod.

Why oldest-first, and why two passes. Each window's *_apy_24h is measured against the stored row 24 hours behind it, so a newest-first walk would leave every 24h column NULL until a second pass. The split is only about what the screener needs soonest: pass 1 restores the live figures, pass 2 restores the chart's depth.

Checks after the backfill.

sql
-- Every active Fluid vault has a row at the latest window.
SELECT count(*) FROM onchain_credit.fluid_vault_rates
 WHERE snapshot_ts = (SELECT max(snapshot_ts) FROM onchain_credit.fluid_vault_rates);
-- Expect the active Fluid registry count (21 as of 2026-09-03).

-- 1x parity: for every single-debt vault the new series must agree with the
-- Liquidity-Layer series for its debt token to annualisation noise. Anything
-- above a basis point means a vault has left 1x (real, and the alert will have
-- said so) or the series is wrong.
SELECT r.strategy_key,
       round(max(abs(v.borrow_apy - l.borrow_apy)) * 10000, 4) AS max_diff_bp
  FROM onchain_credit.fluid_vault_rates v
  JOIN onchain_credit.carry_registry r ON r.vault_address = v.vault_address
  JOIN onchain_credit.fluid_ll_apy l
    ON l.snapshot_ts = v.snapshot_ts
   AND l.token_address = lower(r.config->>'debtAddr')
 WHERE r.protocol = 'Fluid' AND r.status = 'active'
   AND r.config->>'kind' IN ('t1-single','t2-smart-col-debt')
   AND v.snapshot_ts >= now() - interval '30 days'
 GROUP BY 1 ORDER BY 2 DESC;

-- Smart-debt overlay: 0 everywhere today, and any non-zero row is a real
-- vault-level charge, not a defect.
SELECT vault_id, count(*) FILTER (WHERE borrow_apy <> 0) AS windows_with_overlay
  FROM onchain_credit.fluid_vault_rates
 WHERE is_smart_debt AND snapshot_ts >= now() - interval '30 days'
 GROUP BY 1 ORDER BY 1;

Approving a new Fluid carry after this. The refresher covers status IN ('active','proposed'), so a vault that was proposed already has history when it is approved. A vault that goes straight to active without ever sitting in proposed needs one catch-up pass, or its carry shows no funding figure until the 6h cron has filled 30 days. "No funding figure" is the whole behaviour, on every surface: the screener dashes the cells, the home page's rate tape skips the trade rather than ranking it, and the assistant reports nulls for the week. Nothing anywhere treats the missing reading as 0% funding.

bash
scripts/run-cron.sh refreshers/fluid-vault-rates.ts --backfill \
  --vault <0xvault> --from 2025-05-21

Rollback. Additive, so a code rollback needs no database change: the table sits unread and the previous readers go back to the Liquidity-Layer token rate. Do not drop it — the history is expensive to rebuild.

Retiring the old portfolio ledger ​

  • belongs to: migration 095 (retire the old portfolio ledger, -- DESTRUCTIVE) — v0.55.0
  • executed: 2026-09-05

The drop ran on prod with the v0.55.0 release on 2026-09-05: the owner recorded it in #787 ("now that migration 095 has run on prod") and #788 ("found while running the v0.55.0 release"). scripts/ops/scrub-staging-pii.sql and scripts/ops/reseed-staging.sh guarded the relations 095 dropped until the #787 clean-up (#896) removed them, which was safe once the nightly reseed had run against post-095 prod dumps — it had, about ten times. Neither file names the retired ledger now, scripts/ops/scrub-staging.test.ts pins that absence so the names cannot drift back in, and the repartition aside tables (067 / 072) keep the to_regclass pattern itself in use.

The release that deleted the last reader of the old flow ledger ships one hand-run migration and three lines to delete from .env.local. Nothing here is automatic: the migration destroys the only copy of a ledger that was the product for a year, and a code rollback does not roll a DROP back.

1. Deploy the release and watch two ticks go green before touching anything else. The migration is safe only once nothing reads the relations it drops, and "nothing reads them" is something the box tells you rather than something the diff proves:

  • one 6h portfolio tick logs its v2 dual-write: line naming the wallets and the range, with no [fail] beside it;
  • one reconciliation tick (refresh-ledger-reconcile.ts, 40 minutes after the portfolio tick) completes and reports no new disagreement.

Both are in pm2 logs onchain-credit and in the cron log. A tick that has not run yet is not a green tick: wait for it.

The first portfolio tick after this deploy can page on an in-transit position, and that page is not about the drop. The leg-disappearance tripwire (scripts/refreshers/portfolio.ts) now judges escrow legs for the first time — it used to hide them, because the engine served then had no receipt kind able to explain one closing and would have paged with the whole escrowed notional attached. A tracked leg that was in transit at the previous snapshot and whose closing receipt is not in the rebuilt ledger raises the alarm on this tick. Read the wallet and the leg off the line before calling the tick red.

2. Delete the three dead switches from .env.local, on prod and on staging:

PORTFOLIO_LEDGER_SOURCE
PORTFOLIO_LEDGER_WRITE
PORTFOLIO_LEDGER_MODE

They are inert once this release is deployed — no code in it reads them — and that qualifier is why they go after step 1 rather than before it. Until the new build is running, readLedgerSource() reads PORTFOLIO_LEDGER_SOURCE at call time and an unset value resolves to v1. Delete the line first and any restart of the OLD build in the window that follows — deploy.yml reverting to $PREV after a failed deploy, or an unrelated pm2 restart --update-env — serves /portfolio from portfolio_flow_events, a relation that has had no writer since the previous release. Every tracked wallet's history would freeze at that block with nothing to say so: the page looks normal, and the reconciliation alarm, which compares the rebuilt rows, keeps passing.

3. Apply the drop, by hand, once per environment.

bash
cd /opt/onchain-credit
scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)" --allow-destructive

095-drop-old-ledger.sql is tagged -- DESTRUCTIVE, so the ordinary runner and the fixture build both skip it and --allow-destructive is the only way it runs. It drops portfolio_flow_events (with its sixteen hash partitions), portfolio_flow_events_preswap, portfolio_parity_runs, fluid_event_log and fluid_event_coverage, and deletes the old scanner's seven chain_scan_cursors rows. Every statement is IF EXISTS and the delete is a no-op on a second run, so re-running it changes nothing.

Until it ran on prod, the nightly staging reseed brought the dropped tables back — the part of this worth carrying to the next retirement. reseed-staging.sh restores a prod dump, so staging's schema is prod's schema of the night before; scrub-staging-pii.sql therefore had to go on naming the old relations (its TRUNCATE accounts is illegal while a table with a foreign key to it exists, and a scrub that aborts leaves staging serving un-scrubbed production data). Those restored rows were read by nothing. Once the drop had run on prod the next reseed stopped carrying them, the guards became permanent no-ops, and #896 deleted them. The order is one-way: drop on prod, let a reseed prove the dump no longer carries the relations, then tidy the scrub — never the other way round.

And what binds afterwards is the DUMP, not the calendar. reseed-staging.sh takes an optional [path-to.dump] and backup-creddit.sh keeps 14 days, so dumps predating the drop stay restorable for two weeks after it. Reseed — or DR-restore — only from a dump taken after 2026-09-05. An older one still carries the retired ledger, and now that the scrub has stopped naming it the single TRUNCATE aborts on its FK to accounts after the restore and before every leak check, leaving staging serving un-scrubbed production data. Nothing pages when that happens: this cron is not wrapped by run-cron.sh, so it is a log line. The default newest-dump path is always safe; the named-dump argument is the one to think about. The constraint is general, not a detail of this retirement — it applies to every later drop of a relation the scrub used to name, and it expires only when the last pre-drop dump ages out.

Pendle redemption-index factor: first deploy (migration 101) ​

  • belongs to: migration 101 (Pendle redemption-index factor) — v0.59.0
  • executed: unverified

What changes for a reader: a Pendle principal token does not always redeem for one unit of the asset it settles into. Once the yield-bearing asset behind it is written down, the whole fall lands on the PT holder, and the size of that fall is f = min(1, SY.exchangeRate() / YT.pyIndexStored()). Until this release f was read live, used for the mark and thrown away. From here it is recorded on every market-state row, because a holder's accrual line needs f at each purchase block and a dated write-down event is by definition a step in f between two moments. Neither is reconstructible from a read of "now".

Prod, in this order. Nothing here is urgent and nothing here is bulk.

bash
# 1. Apply the migration (additive, two nullable columns; gated manual step on
#    prod). It cannot deadlock the deploy in either order — no prerendered page
#    reads the new columns — and the 6h refresher TOLERATES their absence: it
#    probes information_schema once per run and, until they exist, writes the
#    snapshot without the pair and says so on one line. So a tick that lands in
#    the gap costs the factor for that tick and nothing else. Run it in the same
#    post-deploy window anyway; every tick before it is a market-hour of factor
#    history nobody can get back without an archive read.
cd /opt/onchain-credit
sudo -u postgres psql -d creddit -c \
  "SELECT filename, applied_at FROM onchain_credit.schema_migrations \
    WHERE filename = '101-pendle-redemption-index.sql';"    # expect NO row first
scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)"
#    expect an `APPLY: 101-pendle-redemption-index.sql` line in that output
sudo -u postgres psql -d creddit -c \
  "SELECT filename, applied_at FROM onchain_credit.schema_migrations \
    WHERE filename = '101-pendle-redemption-index.sql';"    # expect ONE row now

# 2. Nothing else is required. The standing 6h refresher fills both columns for
#    every ACTIVE market from its next tick, in the same multicall batch and at
#    the same block as the rest of the row. Confirm after one tick:
sudo -u postgres psql -d creddit -c \
  "SELECT count(*) FILTER (WHERE redemption_index_factor IS NOT NULL) AS filled, \
          count(*) AS rows_today \
     FROM onchain_credit.pendle_market_state \
    WHERE snapshot_ts > now() - interval '7 hours';"

Historical rows stay NULL, deliberately, and are filled ON DEMAND. Every row written before the migration has no factor, and the read path withholds rather than assuming par. Fill a market's history only when a tracked wallet actually holds its PT:

SCOPE, SINCE THE AUTO-BACKFILL SHIPPED. The command below is now for markets the registry already carried when that change landed. A market discovered from then on has its history and factors filled by the 6h refresher itself, in the tick that inserts it (both discovery arms), capped at two markets a tick and run after the snapshot loop; a standing drain returns markets that still hold no API history at all, narrowed through portfolio_held_pts and bounded at the ledger derivation floor, rotating so no market can hold the head of the queue, so a deferred or failed pass retries without an operator. The drain does NOT fill pre-2026-01-01 display history, and it does not refill a market whose archive legs failed — both stay this command's job. So the manual pass is for the backlog, for a market whose automatic pass was short, and for --no-factors display history. It is unchanged, and still idempotent.

THIS BACKFILL IS WHAT TURNS THE ACCRUAL LINE ON FOR AN EXISTING HOLDING ​

Migration 101 is necessary and NOT sufficient, and the shape of the gap is worth stating before someone reports it as a bug. A PT lot locks its yield from the factor at its own fill block (M34), and factorAt will only answer from a stored row at or before that block, within its bound. The 6h refresher fills FORWARD from the deploy — so for a market whose history has not been backfilled, every lot bought before the deploy has no factor, opens unvalued, and withholds that leg's whole accrual line for as long as the lot is open. The position row says so rather than leaving it blank: markWithheld.redemption reads pt-factor-unavailable, whose remedy is exactly the per-market command below.

So for any wallet holding a PT bought before this release, the gated step below is not an optimisation — it is the step that makes the feature do anything at all for that holding. Cost is per market and stated below (~1,500 chain reads per market-year); run it for the markets the query at the end of this section returns and no others.

Nothing is at risk while it is outstanding. A withheld line is a dash with a named reason, never a wrong number, and the market line is unaffected throughout. Prod holds zero users after the 2026-09-10 wipe, so today the set is empty; it matters from the first wallet registered with pre-existing Pendle history.

bash
# Cost first, honestly. Per row: one block resolution — which is one DefiLlama
# call plus one or two eth_getBlockByNumber verification reads, or a full
# ~25-probe bisect when Llama is down — and one multicall of two archive calls.
# Call it 4 to 5 chain reads per row, so a market-year is ~1,500, not ~730.
# Preview it (the dry run probes ONE point live, so it also tells you the chain
# is reachable at that depth and whether the market is impaired):
scripts/run-cron.sh backfill-pendle-history.ts --market 0x8cef2919… --dry-run

# Then the real pass for that one market:
scripts/run-cron.sh backfill-pendle-history.ts --market 0x8cef2919…

Do NOT run it over all 76 markets. A bulk pass is on the order of 100k chain reads to fill history for markets nobody holds. Running the script without --market is still supported for its original job (display history for the /carries term surfaces); pair it with --no-factors there, which restores the API-only behaviour and skips the chain reads entirely.

It is safe to re-run. The conflict clause writes the pair only where the stored one is NULL and the read produced one, so a second pass over a finished market updates no row, a failed read never nulls a factor already banked, and no API-sourced column can overwrite a cron snapshot. A row that already carries a block anchor is read AT THAT BLOCK, so it keeps describing a single block.

Which markets are worth it. The ones a tracked wallet holds, matured or not — and a PT held as collateral counts. The four arms below are the repo's own held-by-anyone probe (PENDLE_PT_REFERENCED_SQL in scripts/refreshers/pendle-markets.ts): a directly held PT on either ledger, plus a PT sitting in any venue's accounting/asset slot, which is the arm that finds a levered PT loop on Morpho or Aave. Scanning only pendle:pt:% keys would miss exactly those legs, so their history would never be filled and their accrual line would be withheld indefinitely.

sql
WITH held AS (
  SELECT DISTINCT lower(split_part(s.position_key, ':', 3)) AS pt
    FROM onchain_credit.portfolio_position_snapshots s
   WHERE s.venue = 'pendle'
  UNION
  SELECT DISTINCT s.accounting_asset
    FROM onchain_credit.portfolio_position_snapshots s
   WHERE s.accounting_asset IS NOT NULL
  UNION
  SELECT DISTINCT f.asset
    FROM onchain_credit.portfolio_flow_events_v2 f
   WHERE f.asset IS NOT NULL
  UNION
  SELECT DISTINCT lower(split_part(f.position_key, ':', 3))
    FROM onchain_credit.portfolio_flow_events_v2 f
   WHERE f.venue = 'pendle'
)
SELECT p.market_address, p.pt_symbol, p.status,
       count(*) FILTER (WHERE s.redemption_index_factor IS NULL) AS unfilled_rows,
       count(*)                                                  AS total_rows
  FROM onchain_credit.pendle_markets p
  JOIN onchain_credit.pendle_market_state s
    ON s.chain_id = p.chain_id AND s.market_address = p.market_address
 WHERE p.pt_address IN (SELECT pt FROM held)
 GROUP BY p.market_address, p.pt_symbol, p.status
HAVING count(*) FILTER (WHERE s.redemption_index_factor IS NULL) > 0
 ORDER BY unfilled_rows DESC;

The bound, so a NULL stretch is read correctly. The reader takes the latest non-null factor at or before a moment and refuses to carry it beyond 18 hours for a 6h cron row or 48 hours for a daily backfill row. Two of the writer's own windows is room for one missed tick; the cron gets a third because its rows are stamped with the window floor but read at the head block minutes later, so at a flat 12 hours the replacement row after a single missed tick would arrive just after the previous one expired and a live figure would blink to a dash for those minutes. Past the bound the reader returns nothing and the value that depended on it is withheld. So a gap in this series shows up as a missing figure, never as a PT quietly marked at par through an impairment.

A matured market's series ends at maturity. The 6h snapshot arm visits status='active' markets only, so no new factor rows appear for a market once it matures. That is not a gap in the mark: at and after maturity the snapshot stores qty_underlying = qty x f, so the factor for a held leg is recoverable per spine row as qty_underlying / qty — never par. What the stored series alone cannot give is f at a flow block no snapshot covers, and the step that makes a dated write-down event. Widening the snapshot arm to held matured markets is a follow-up, deliberately not done here; the reader's staleness rule makes the absence explicit rather than extrapolating.

Rollback. Additive, so a code rollback needs no database change: the two columns sit unread. Do not drop them; a filled history is expensive to rebuild.

Pendle PT payout assets: first deploy (migration 102) ​

  • belongs to: migration 102 (the first three Pendle PT payout assets) — v0.59.0
  • executed: unverified

apply it after the deploy, not before. All three rows (USDat, trUSD, iUSD) carry wallet_tracked = true, so applied first against the old bundle the idle sweep would start reading these balances while the previously-compiled disclosed-holdings constant knows nothing about them. Nothing else is required: the three price tapes are bought automatically on the first standing refresh-assets tick after the DEPLOY (not after the migration), because the feed set answers from the compiled seed and the database is an overlay on top of it — docs/database.md's portfolio_tokens row carries that argument, the three 90-day executions and the ~12-credit one-off cost. scripts/backfill-token-price-bars.ts is a REPAIR tool here, not a gate.

The coverage rule: first deploy (migration 105) ​

  • belongs to: migration 105 (the coverage rule: 18 new rows, 11 rows swept, 11 rows retired) — v0.64.0
  • executed: 2026-09-17

Run 2026-09-17 (v0.64.0): applied after the deploy by the bare runner at 13:22:21Z, in one run with 106 and 107; the three counts read 18 | 11 | 25.

Apply it after the deploy, not before. 105 flips wallet_tracked on for eleven rows, four of which (WBTC, cbBTC, LBTC, eBTC) the OLD bundle reports through its compiled disclosed-holdings constant. Applied first, the old idle sweep would start reading those balances — not doubled (the old bundle filtered its disclosed list against the stored spine, so a holding the pipeline had started storing was reported once), but served into the wrong view: the old bundle's one branch for a book-NULL idle wallet leg put such a row inside the USD statement, so a bitcoin balance would have sat in the dollar view for the length of the window. Applied after the deploy there is no such window, because the new bundle serves a no-base leg into the All view only.

The three parts do not all take effect at the same moment, and it is worth knowing which is which while the window is open. The eighteen new rows are live at the deploy: the registry overlays the database on top of the compiled seed, and no row exists for any of them yet, so the seed's row stands and they are swept (and their feeds declared) from the first process start. The eleven tracking flips and the eleven retirements wait for this file: those addresses do have rows, and the sweep universe is a direct read of portfolio_tokens.wallet_tracked where status = 'active', so the database's value wins until the migration lands. Between the deploy and the migration a bare WBTC balance is in NEITHER place — not swept, and no longer disclosed — so it is absent rather than doubled, which is the smaller of the two failures and the one this order chooses. Do not leave the runbook half-run overnight.

bash
# PROD, after the release deploys.
cd /opt/onchain-credit && scripts/ops/migrate.sh "$DATABASE_URL"
# Expect 105-coverage-rule.sql in the ledger, and these three counts: 18 | 11 | 25
sudo -u postgres psql -d creddit -c \
  "SELECT count(*) FILTER (WHERE source = 'venue-live')                AS added_18,
          count(*) FILTER (WHERE status = 'retired')                   AS retired_11,
          count(*) FILTER (WHERE wallet_tracked AND book IS NULL)      AS no_base_tracked
     FROM onchain_credit.portfolio_tokens WHERE chain_id = 1;"

Nothing else is required for the PRICES. The nineteen rows declaring a dune_tape are in the standing feed set from the first process start after the code ships — the set answers from the COMPILED seed and the database is an overlay on top of it — so the mirror's auto-backfill on add buys 2026-01-01 → now on the next 0 */6 refresh-assets tick, in about three Dune executions per batch, bounded by DUNE_MAX_CREDITS_PER_RUN. scripts/backfill-token-price-bars.ts is a REPAIR tool here, not a gate.

The account wipe that goes with it is a separate step, listed under the gated repairs below: the sweep universe changes, so every stored history is a history of a narrower universe than the one the release reads.

Migration 106 (retire the discovery scope rows) ​

  • belongs to: migration 106 (the legacy-code cleanup, issue #909) — v0.64.0
  • executed: 2026-09-17

Run 2026-09-17 (v0.64.0): applied at 13:22:21Z; 11 portfolio:discover:% rows before, 0 after.

Deletes every chain_scan_cursors row under portfolio:discover:%: the per-wallet discovery watermarks that migration 061 superseded with the certificate on accounts. The release carrying it removes the last writer (the one-release dual-write) and the last readers (the pre-061 fallbacks), so nothing reads what it deletes. Prod held 11 such rows when the file was written; staging holds none (the nightly scrub deletes them).

Additive-shaped (a DELETE, no DDL, no -- DESTRUCTIVE tag), so staging auto-applies it. On prod run scripts/ops/migrate.sh after the deploy, in the same session as the other migrations of the release; order against the deploy does not matter for correctness:

  • before the deploy, the previous release re-creates a row on its next certificate stamp, and nothing reads it;
  • after a code rollback, the same: the previous release only ever wrote these rows on a database that has 061, and read them only when 061's columns were missing.

Verify with SELECT count(*) FROM onchain_credit.chain_scan_cursors WHERE scope LIKE 'portfolio:discover:%' (expect 0).

Follow-up (code, after this step): the staging scrub (scripts/ops/scrub-staging-pii.sql), the reseed leak check (scripts/ops/reseed-staging.sh), the user wipe (scripts/ops/reset-portfolio-users.ts) and scripts/ops/scrub-staging.test.ts keep the portfolio:discover:% prefix for this release, because a prod dump taken before 106 still carries prod's enrolled-wallet list under it. Once 106 has run on prod and a nightly reseed has restored a dump taken after it, drop the prefix from all four together.

Migration 107 (narrow the portfolio book CHECKs) ​

  • belongs to: migration 107 (the legacy-code cleanup, issue #909; specified as 078) — v0.64.0
  • executed: 2026-09-17

Run 2026-09-17 (v0.64.0): applied at 13:22:22Z with no replay running and no lock timeout; neither constraint names 'BTC' and no portfolio_pos_book_chk row exists.

Drops 'BTC' from portfolio_pos_book_chk2 (the partitioned snapshot spine; the parent carries it to every monthly partition, and a database where the snapshot repartition 067 never ran has the older name portfolio_pos_book_chk, which it drops too) and from portfolio_tokens_book_chk. Self-guarding: it RAISES, changing nothing, while any book='BTC' row survives in either table. Prod held none on 2026-09-17.

Untagged, so staging auto-applies it; on prod run scripts/ops/migrate.sh after the deploy. The validation scan holds ACCESS EXCLUSIVE on the spine for its duration (77 MB on prod when written: well under a second), so the 6h tick or a page load that arrives during it waits rather than fails.

The reverse wait can fail it. migrate.sh sets lock_timeout=10s, and a backfill replay holds its transaction on the spine for minutes, so 107 arriving during one aborts with canceling statement due to lock timeout. Nothing changes (the file is one transaction) and it is safe to re-run. The nightly 02:15 backup's pg_dump holds a lock on the table for the whole dump, so it causes the same abort: do not run 107 across that window. Before running it on prod, check that no replay is in flight:

sql
SELECT count(*) FROM onchain_credit.portfolio_backfill_state WHERE status = 'running';  -- expect 0

On staging the same abort turns the deploy job red after the build and before the restart; re-run the deploy workflow. Every staging deploy re-runs 107 until prod has applied it, because each nightly reseed restores prod's migration ledger. Verify:

sql
SELECT conrelid::regclass, pg_get_constraintdef(oid)
  FROM pg_constraint
 WHERE conname IN ('portfolio_pos_book_chk', 'portfolio_pos_book_chk2', 'portfolio_tokens_book_chk')
   AND conrelid::regclass::text NOT LIKE '%\_preswap';

Expect no 'BTC' in any definition and no portfolio_pos_book_chk row. (The filter leaves out 067's aside table, portfolio_position_snapshots_preswap, which keeps its old constraint wherever it still exists.) A code rollback needs nothing: the previous release cannot write 'BTC' either.

Migration 108 (drop the token_basis shadow table) ​

  • belongs to: migration 108 (the legacy-code cleanup, issue #909) — v0.64.0
  • executed: 2026-09-17

Run 2026-09-17 (v0.64.0): the only pending tagged file after 105–107; applied with --allow-destructive at 13:22:42Z, and to_regclass reads NULL.

Drops token_basis_dune_shadow, the scratch table of the one-time mirror rebuild of token_basis (see data-pipeline), which ran on prod on 2026-07-20. The two scripts that used it are deleted in the same release.

Tagged -- DESTRUCTIVE, so neither environment auto-applies it. On prod, after the deploy:

bash
cd /opt/onchain-credit && scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)" --allow-destructive

--allow-destructive applies every pending tagged file, so check first that 108 is the only one pending (ls scripts/sql against SELECT filename FROM onchain_credit.schema_migrations). Staging needs no step: it restores prod's dump nightly, so the table leaves staging with the first dump taken after the prod drop. Verify with SELECT to_regclass('onchain_credit.token_basis_dune_shadow') (expect NULL).

Staging env: the JIT positions fast path matches production (#909) ​

  • belongs to: the release carrying #909 (PR #912) — v0.64.0
  • executed: 2026-09-17

Production's .env.local sets JIT_LEDGER_LAG_BLOCKS=200, which turns the JIT positions fast path on; staging leaves it unset, so staging tests the default (off). Align staging once:

bash
# on the box
grep -q '^JIT_LEDGER_LAG_BLOCKS=' /opt/onchain-credit-staging/.env.local \
  || echo 'JIT_LEDGER_LAG_BLOCKS=200' >> /opt/onchain-credit-staging/.env.local
pm2 restart onchain-credit-staging --update-env

It is a configuration match rather than a live path: staging runs no ingester process, so its ledger tip trails head by far more than 200 blocks except right after an attended ingester hand-run, and a page load full-reads positions until then. See Environment variables.

The price-source rule: first deploy (migration 109) ​

  • belongs to: migration 109 (the price-source rule: the four rows 105 left unpriced) — v0.65.0
  • executed: 2026-09-18

Applied 2026-09-18 08:37:09Z on prod, after the v0.65.0 deploy (app + ingester restarted 08:36Z), with the backfill queue idle (done|4, empty|1). migrate.sh applied 109 alone; the checks read 22 for no-base tracked and the four rows exactly as expected (AA_FalconXUSDC USD (null) composed getter primary_buffer, BTC.b NULL llama_aggregate market (null) secondary, USDai USD llama_aggregate market (null) secondary, wFalconX USD (null) composed getter primary_buffer). The ingester freshness alarm read both arms ok at 08:37Z (13 feeds within the 6h bound, worst 13 min). The live sync (#919) shipped in the same release with no data step; no live tip existed on prod at 08:40Z (no page load since the deploy).

Apply it after the deploy, in the release's own migrate.sh run. It ships alone: 105 is already on prod — applied 2026-09-17 13:22:21Z alongside 106–108 with v0.64.0 — so this file is the only unapplied one the runner finds, and the state it lands on is the one that release left.

What it changes. 105 left four tracked rows with no price feed at all, valuing to a dash, and on prod today all four still read book NULL, feed NULL, valuation market. 109 gives each of them a price: BTC.b and USDai take feed = 'llama_aggregate', a fourth feed kind that fills the same hourly bar table from DefiLlama's Coins API; USDai also takes the dollar book; and the FalconX pair (AA_FalconXUSDC and its 1:1 wrapper wFalconX) becomes a composed dollar holding valued at the credit vault's own NAV. It adds no row, deletes none, and changes no quantity. It widens the feed CHECK to admit the fourth value, dropping and re-adding it by name so the file is idempotent.

Why after the deploy, and why it is sharper than 105's reason. All four rows already EXIST in portfolio_tokens, so unlike 105's eighteen new rows none of this takes effect at the deploy: the registry overlays the database on top of the compiled seed field by field, and a column the database answers — NULL included — wins. Between the deploy and this file the four rows behave exactly as they do today.

Applied FIRST, against the old bundle, three of the four rows go wrong and nothing is permanent. Every line below was read off the deployed loader and the deployed valuation path rather than reasoned from the column, which is the only way to get this right: the old bundle's loader admits three feed values (dune_tape, dune_dex_ratio, pool_quote) and maps anything else to NULL, and the overlay installs that NULL as the answer. To that bundle llama_aggregate is not "a standing feed" — it is no feed at all, and every set that decides a CSV, the spike gate or an alert is computed off the overlaid row.

  1. BTC.b: nothing changes. Its feed arrives NULL, which is the state 105 left it in, so it is in no CSV, no standing set and on no alert, and it keeps the dash it has today. The two hazards the row invites you to assume are both impossible for that same reason: an old bundle can neither capture its hours into the Dune tape nor page for a dark feed, because each of those is judged off a feed value it reads as absent rather than as unrecognised.
  2. USDai: the real hazard, and on its own the reason for the ordering. It arrives booked USD, class = 'par', valuation market, feed NULL — the shape booking it is only safe without because 109 declares the feed in the same file. That bundle has nowhere to buy the mark, so the leg is stored with its redemption line answering identity (quantity × 1, every holder, no read) and its market mark withheld: face value on one basis, a dash beside it on the other, and nothing flagged, because the incomplete flag reads the mark in force.
  3. The FalconX pair: worse than a dash — the holding disappears. Both arrive booked USD and variable_rate with rate_kind = 'getter' and a getter kind that bundle has no reader for. An unknown kind logs one line and answers null; neither address has a stored share-rate series to fall back to (checked read-only on prod: no token_yield_apy row carries a share_rate for either), so the redemption resolver raises and the snapshot skips the leg (M9). No row is stored at all — the holding is in no band, no total, and not in the outside group either, since that group is where an EXCLUDED-book row goes and this row is no longer EXCLUDED. Nothing pages either: a withheld leg does not fail the run, so the only trace is one [rate-getters] no reader for rate_getter kind line in the cron log. Today the two are listed under "outside the yield book" with a dash; in that window they are not listed at all.
  4. The widened CHECK is harmless in both directions. It only admits one more value, and the old bundle writes none of them.

So the order stands for (2) and (3) rather than for anything irreversible. No bar can be written under the wrong source — nothing puts these rows in a CSV — and a position snapshot taken inside the window is re-derivable like any other. What applying after the deploy buys is that no holder is shown a face value nothing can contradict, or a holding that vanished.

bash
# PROD, after the release deploys. 109 is the only file pending.
cd /opt/onchain-credit && scripts/ops/migrate.sh "$DATABASE_URL"
# Expect 109-price-source-rule.sql in the ledger, and these four rows:
#   BTC.b           book NULL | feed llama_aggregate | market   | liquidity secondary
#   USDai           book USD  | feed llama_aggregate | market   | liquidity secondary
#   AA_FalconXUSDC  book USD  | feed (null)          | composed | liquidity primary_buffer
#   wFalconX        book USD  | feed (null)          | composed | liquidity primary_buffer
sudo -u postgres psql -d creddit -c \
  "SELECT symbol, book, feed, valuation, rate_kind, liquidity
     FROM onchain_credit.portfolio_tokens
    WHERE chain_id = 1
      AND address IN ('0xb0f70c0bd6fd87dbeb7c10dc692a2a6106817072',
                      '0x0a1a1a107e45b7ced86833863f482bc5f4ed82ef',
                      '0xc26a6fa2c37b38e549a4a1807543801db684f99c',
                      '0x4614f7a56a3eb83b2ff9fa4b4b9575b28fb68644')
    ORDER BY symbol;"
# …and the CHECK now admits four values, not three:
sudo -u postgres psql -d creddit -c \
  "SELECT pg_get_constraintdef(oid) FROM pg_constraint
    WHERE conname = 'portfolio_tokens_feed_chk';"
# ONE of 105's three counts moves, and only after this file: the no-base one, 25 -> 22,
# because USDai and the FalconX pair stop being booked against nothing. The other two
# (18 added, 11 retired) are 105's and do not move. Read on prod 2026-09-17: 18 | 11 | 25.
sudo -u postgres psql -d creddit -c \
  "SELECT count(*) FILTER (WHERE wallet_tracked AND book IS NULL) AS no_base_tracked_22
     FROM onchain_credit.portfolio_tokens WHERE chain_id = 1;"

Nothing else is required for the PRICES. Declaring a feed enrols a token in the mirror's auto-backfill on add, and the aggregate leg loads its own floor: on the first 0 */6refresh-assets tick after this file is applied it buys 2026-01-01 → now for both rows — about 6,200 hours each, a week of hours per request, so roughly 38 keyless HTTP requests per token, paced 250ms apart, under a minute of wall clock and no Dune credits at all. There is no bulk tool to run and none is owed. The FalconX pair needs no price load whatever: it is composed, so its mark is the vault's NAV read at each leg's own block times USDC's existing bar.

The re-derive question is answered at run time, not by this page. 109 changes how four rows are VALUED, and a history stored before it keeps the old answer: a USDai leg derived while the row was booked against nothing carries book = 'EXCLUDED' and no mark, so once this file books it USD the same holding joins the dollar view part-way through its own history with nothing behind the join.

rows_on_the_four is the whole gate — not the account count. Whether prod is empty is a fact with a date on it and it decays between the day this page is written and the day it is run: the v0.64.0 account wipe emptied prod on 2026-09-17, and a read-only check during review later the same day found 5 accounts and 577 snapshot rows again, with rows_on_the_four still 0. That is the point rather than a footnote — a signed-in account holding none of the four assets owes this migration nothing, so the count that decides the branch is the second one and the first is only context for the run note. Read the scope immediately before applying:

sql
-- read-only, on prod, just before migrate.sh. `accounts` is CONTEXT — record it, do not
-- gate on it. `rows_on_the_four` is what decides the branch below, and it is normal for
-- `accounts` to be non-zero while it is 0.
SELECT (SELECT count(*) FROM onchain_credit.accounts) AS accounts,
       (SELECT count(*) FROM onchain_credit.portfolio_position_snapshots
         WHERE accounting_asset IN ('0xb0f70c0bd6fd87dbeb7c10dc692a2a6106817072',
                                    '0x0a1a1a107e45b7ced86833863f482bc5f4ed82ef',
                                    '0xc26a6fa2c37b38e549a4a1807543801db684f99c',
                                    '0x4614f7a56a3eb83b2ff9fa4b4b9575b28fb68644')) AS rows_on_the_four;

rows_on_the_four = 0 → record both figures in this step's run note and skip the re-derive, whatever accounts says — including a non-zero accounts, which is the expected reading now that prod takes sign-ins again: no stored leg is valued off any of the four rows, so there is nothing for a re-derive to restate.

rows_on_the_four > 0 → it is owed, in the same window as the migration. List the wallets (SELECT DISTINCT wallet FROM onchain_credit.portfolio_position_snapshots WHERE accounting_asset IN (…the same four…)) and re-derive each one RANGED from its own floor to its own cursor, the shape the forced-pull step spells out in full (scripts/build-shadow-ledger.ts --wallet <w> --from <floor> --to <cursor> --range 50000, floor and cursor read per wallet, never copied from a page). If the list is long enough that the campaign costs more than the history is worth, wipe instead, exactly as 105 did — but then it is a gated step of its own and needs Fred's approval before it runs.

No ISR step. /portfolio IS prerendered, but as a static shell with no revalidate window (next build lists it ○ with no timer, unlike /carries at 5m or /asset-profiles at 1h). Every figure a signed-in reader sees on it is fetched client-side from the portfolio APIs, so the new rows appear on the next request with no page to re-render and nothing to purge. No screener page reads portfolio_tokens.feed, so none of the timed routes is stale either.

And no prerender/migrate deadlock, the trap a registry migration has to clear before the order above is safe: 109 adds no column. It widens one CHECK and updates four rows, so the bundle the staging deploy prerenders against reads exactly the columns it already reads, whether or not this file has been applied yet.

Rollback. The UPDATEs are reversible by hand (set the four rows back to feed NULL / book NULL / valuation market). A code rollback needs that revert, in the same window: rolling the bundle back while these rows stand puts the product in exactly the state (2) and (3) above describe — USDai at an uncontradicted face value, the FalconX pair gone from the page — which is the same window this ordering exists to avoid, entered from the other end. The feed value itself is harmless to an older bundle (it reads as no feed); book and rate_kind are what have to go back. Leave the widened CHECK in place — it admits a superset and nothing breaks on it.

Hourly bars only, and the pool-quote feed retired (migration 110) ​

  • belongs to: migration 110 (pricing categories sub-PR A: hourly bars only, pool feeds and the aggregator tip removed) — v0.68.0
  • executed: 2026-09-23

Run 2026-09-23 (v0.68.0), 13:24Z on prod, after the 13:13Z deploy and after 111/112 had gone on at 13:06Z — the order this release's step list requires. Applied by hand with --allow-destructive, as the file's tag demands; the bare runner had already listed 111 and 112 before it was run. The window between the deploy and this file, in which PST and sUSDai read as having no standing feed, was eleven minutes. The hand-run tick at 13:26Z is what closed it.

It is tagged -- DESTRUCTIVE and it means it. scripts/ops/migrate.sh SKIPS a tagged file unless it is handed --allow-destructive, so neither the staging deploy nor the prod migrate.sh run applies this one: it is a hand step, on staging first and then on prod, AFTER the deploy.

What it deletes, and why deleting is the honest answer. Two populations, both of them rows no writer can ever replace (bars are inserted ON CONFLICT DO NOTHING and 055 REVOKEd DELETE from the app roles):

  1. The fine-grained bars. 054 created the bar table on a 300-second grid, for a channel that bought named 5-minute bars at a wallet's flow instants. That channel had no caller after v0.55.0 and this release deletes it, so what is left of it is a population of off-hour rows the spike gate can never judge — it reads the hourly grid, because convicting a spiked hour needs its two NEIGHBOURS to agree and an off-hour row beside it defeats that test. A bad one among them can be served as a mark for ever. The largest block is one staging incident's 12,412 contiguous rows.
  2. The pool-quote bars (source = 'pool:fluid_dex_t1'). The feed is retired, so leaving them would pin PST's and sUSDai's series to a feed nothing fills any more, permanently and invisibly.

The second deletion opens a hole, and the file closes the door that would have kept it open. The feeds PARTITION the rows, so while the pool feed ran it was the ONLY writer either of those two had: deleting its bars leaves a hole over exactly the span it covered. Two properties of the six-hourly sync would have made that hole permanent: floor_loaded is sticky (written existing OR EXCLUDED, and the retired pool leg set it true on both rows every tick, so the planner would never floor-load them again), and the cursor is monotonic (GREATEST(existing, EXCLUDED), so it still points at the top of the hole and the next incremental window would open above it). So the migration DELETES both rows' sync-state rows. 098 creates those lazily on a token's first sync attempt, so a row without one is exactly a row that has just joined the standing set: the planner bootstraps it from its stored bars instead of a cursor, and the next tick either floor-loads it from the 2026-01-01 mirror floor or catches it up from its oldest surviving bar. Either covers the span.

What that does not promise. The tape is quiet for these two assets — the whole reason they had a feed of their own — so the re-offered span may come back thin, and for PST close to empty. The plan accepts that (R9) and names DefiLlama's hourly history as PST's filler, which arrives with the live-price work. The guarantee here is that the span is ASKED FOR by every leg that can fill it, rather than skipped silently.

No wallet is repaired and no mark is restated, because the release that carries this deletes every tracked wallet: there is no stored position history for a deleted bar to change the value of.

What else it does. It verifies every remaining bar_ts is on the hour and RAISES naming the offenders if not (an off-hour row that is not from the deleted channel is a writer nobody has accounted for); replaces the 300-second grid CHECK with an hourly one; moves the two pool-quoted registry rows to feed = 'dune_tape' with a NULL feed_config; narrows the feed CHECK to the three remaining kinds; and drops the shape-CHECK clause that required a pool-quoted row to carry its wiring.

Why after the deploy, and why the window should be short. Between the deploy and this file the two rows still hold pool_quote, a kind this release's registry loader does not admit, so it installs NULL over it and both read as having NO standing feed: no bars are bought for them, the dark-feed alert does not watch them, and their marks walk back to what is already stored. Nothing is lost permanently — a bar not bought in that window is bought by the next tick's own gap-covering sync — but the shorter the window the fewer hours have to be caught up.

The rollback direction is safe for a different reason, not the same one. An older bundle reads dune_tape as the tape kind it already knows, so it does not see the two rows as unfed: its pool leg finds no pool-quoted row to serve, its partitioner puts both on the standard CSV, and its tape leg syncs them. Hourly bars satisfy the old 300-second CHECK, so nothing it writes is refused either. The one thing to watch is that the old bundle's COMPILED pool-quote defaults are overridden only by a registry read that SUCCEEDS: a rolled back process whose registry read fails runs its pool leg off the compiled list and writes fresh pool:fluid_dex_t1 bars back into the hours this file cleared, which nothing in the database refuses (the feed CHECK constrains portfolio_tokens, not token_price_bars.source). A rollback that lasts long enough to matter therefore ends with this file re-applied.

bash
# STAGING first, then PROD, after the release deploys.
cd /opt/onchain-credit && scripts/ops/migrate.sh "$DATABASE_URL" --allow-destructive
# Check what the flag would let through BEFORE running it: it is not scoped to 110.
#   psql> SELECT filename FROM onchain_credit.schema_migrations ORDER BY filename DESC LIMIT 5;
# If another DESTRUCTIVE file is still pending on this box, apply 110 BY HAND instead:
#   sudo -u postgres psql -v ON_ERROR_STOP=1 -X -q -1 -d <db> \
#     -f scripts/sql/110-hourly-bars-only.sql
#   sudo -u postgres psql -q -d <db> -c "INSERT INTO onchain_credit.schema_migrations(filename) \
#     VALUES ('110-hourly-bars-only.sql')"

If it fails on lock_timeout, re-run it. Adding a validated CHECK takes ACCESS EXCLUSIVE on token_price_bars for the whole validation scan, and migrate.sh runs under lock_timeout=10s: a live reader holding the table at that moment aborts the file. The file is idempotent, so the fix is to run it again when the box is quiet.

sql
-- Expect: zero off-hour bars, zero pool-sourced bars, the two rows on the tape, and no
-- sync-state row left for either of them (the next tick recreates both).
SELECT count(*) FROM onchain_credit.token_price_bars
 WHERE extract(epoch FROM bar_ts)::bigint % 3600 <> 0;                  -- 0
SELECT count(*) FROM onchain_credit.token_price_bars
 WHERE source IN ('dune:prices.minute', 'pool:fluid_dex_t1');           -- 0
SELECT symbol, feed, feed_config FROM onchain_credit.portfolio_tokens
 WHERE address IN ('0x22ae3d9a738471f405169af055d31c687087d4c7',
                   '0x0b2b2b2076d95dda7817e785989fe353fe955ef9');       -- both dune_tape, NULL
SELECT count(*) FROM onchain_credit.token_price_sync_state
 WHERE chain_id = 1
   AND token_address IN ('0x22ae3d9a738471f405169af055d31c687087d4c7',
                         '0x0b2b2b2076d95dda7817e785989fe353fe955ef9'); -- 0
sql
-- AFTER THE NEXT SIX-HOURLY TICK, on the same box: both rows are back, floor-loaded, with
-- a cursor. `last_bar_ts` may still be NULL for PST if the tape printed nothing for it,
-- which is the accepted R9 outcome and not a failure of this step.
SELECT token_address, last_bar_ts, floor_loaded, consecutive_failures
  FROM onchain_credit.token_price_sync_state
 WHERE chain_id = 1
   AND token_address IN ('0x22ae3d9a738471f405169af055d31c687087d4c7',
                         '0x0b2b2b2076d95dda7817e785989fe353fe955ef9');

Rollback. The deleted bars are gone: the purge is not reversible, and it is not meant to be (nothing reads them, and the release wipes every wallet). The CHECKs, the two registry rows and the two sync-state rows are all reproducible by hand, and an older bundle needs none of them reverted — it reads an hourly bar and a dune_tape feed exactly as this one does.

The declared route and the pricing categories (migrations 111 and 112) ​

  • belongs to: migrations 111 (pricing categories sub-PR B: the declared route, the capacity table, five category moves and two feeds withdrawn) and 112 (sub-PR E: the reported-volume measurement kind) — v0.68.0
  • executed: 2026-09-23

Run 2026-09-23 (v0.68.0), 13:06Z on prod, BEFORE the 13:13Z deploy, by hand from the staging checkout's copy of the release and recorded in the ledger by hand — migrate.sh reads the SQL directory of the checkout it is invoked from, and /opt/onchain-credit did not hold these files until the deploy. COINGECKO_API_KEY and DUNE_QUERY_ID_DEX_MARKET=8808795 went into /opt/onchain-credit/.env.local in the same 13:06Z window, so the first process start after the deploy saw both. 112's widened CHECKs were in place before the weekly market job's first run at 13:23Z, which is the ordering that file exists for.

It is additive, but it goes on BEFORE the deploy and BY HAND — the opposite of the usual instruction for an additive file on both counts, and the reason is what the new code reads rather than what the file writes. registry-load.ts selects the six new columns by name from the first process start, and a SELECT naming a column that does not exist throws. initRegistries is fail-open, so nothing deadlocks; what happens instead is that every process on the box — the app and every cron — answers from the SHIPPED SEED until the file lands, and a row that exists only in the database (a stablecoin admitted with sync-portfolio-tokens.ts --approve, any operator row edit) has no seed to fall back to. It vanishes from the registry for that window, and a wallet holding it values it as uncovered on every page load.

What applying it early costs instead, stated because it is the asymmetry being traded: against the OLD bundle, sDAI, sUSDS, srUSDe and sUSDD stop being marked off their own bars and start composing — the right answer arriving a few minutes ahead of the code that explains it — and USD3 starts asking for a tape the old bundle can only fill from Dune, which prints nothing for it. sGHO and sUSDf lose their feed in the same file, and the old bundle still grades feed quality over the rows that compose WITHOUT a primary buffer, which both of them still are, so for the length of the window that grader is asked about two rows whose feed is now NULL; it grades the bars they already hold and nothing acts on the verdict. All of that is a hole, not a wrong number, and it closes on the first tick after the deploy. Minutes of it is strictly cheaper than a registry overlay that is dark for every process on the box.

112 GOES ON IN THE SAME STEP, immediately after it, for a different reason. It is additive too — it drops and re-adds the two CHECKs on token_pricing_measurements so the vocabulary admits reported_median_daily_volume, the median daily volume the price vendor reports across exchanges and DEXes, which is what the category test's volume bar is judged on. Nothing READS it early, so the registry-dark argument above does not apply to it; what does apply is the other direction. The weekly market job writes that kind from its first run after the deploy, and against an unwidened CHECK the database refuses the INSERT. Applying it with 111 costs nothing either way: the previous release never writes the kind, and its reader drops a row whose kind is outside its own list, so a reading of this kind sitting in the table is invisible to it rather than a surprise.

What it carries. Six nullable columns on portfolio_tokens (mint_terms, redeem_terms, capacity_reader, terms_verified, loopable, loopable_verified), the append-only token_pricing_measurements table, one new registry row (USDD 2.0, 0x4f8e5de4…cd1a, which is what sUSDD composes onto), and a generated block of UPDATEs: the declared route on every yield-bearing row, five category moves (sDAI, sUSDS, srUSDe and sUSDD to redemption-priced; USD3 to market-priced), and the two feeds withdrawn from sGHO and sUSDf, which change category and class neither of them and simply stop buying bars nothing marks off.

Why by hand, and why the standard runner CANNOT do this one. migrate.sh resolves its SQL_DIR from the checkout it is invoked from (scripts/ops/migrate.sh, the dirname "$0"/../sql line), and /opt/onchain-credit is a checkout tracking origin/main that receives this release only inside the deploy pipeline, at its own git fetch + git reset --hard FETCH_HEAD step (deployment §2.1). Before the deploy there is no scripts/sql/111-pricing-terms.sql on that box at all. Run there, the runner loops over the files that ARE there, finds nothing pending, prints migrate creddit: 0 applied, N total on disk and exits 0 — which is exactly what an already-applied migration looks like, so the step reports success for having done nothing, and 111 is then swept up by step 4's unscoped --allow-destructive run AFTER the deploy. That is the registry-dark window this entry exists to avoid, arrived at silently. So the file is applied by hand from the release's own copy, which is the same shape the 110 entry documents as its own by-hand fallback. Pointing the runner at a checkout that DOES hold the file is not the same step either: it would apply every file pending in that checkout rather than this one, which is a blast radius no release step should carry.

Where the release's copy is, before the deploy. /opt/onchain-credit-staging is on the same box, tracks origin/staging, and the release is the merge of staging into main (deployment §3) — so at release time its checkout holds this exact file, and staging's own deploy has already applied it to creddit_staging. Confirm that before trusting it: if the commit does not match the release, scp the file from a local checkout of the release commit instead.

bash
# PROD, BEFORE the release deploys. 1. the file must be THE RELEASE'S copy.
git -C /opt/onchain-credit-staging rev-parse HEAD     # = the release PR's head commit
sha256sum /opt/onchain-credit-staging/scripts/sql/111-pricing-terms.sql   # = your checkout's

# 2. apply it as the owner, in one transaction and under the runner's own timeouts (the
#    file carries no transaction control and is not tagged -- NO-TRANSACTION, so this is
#    exactly what migrate.sh would have done with it). If it aborts on lock_timeout a
#    live reader held the table; the file is idempotent, so run it again when it is quiet.
sudo -u postgres env "PGOPTIONS=-clock_timeout=10s -cstatement_timeout=300s" \
  psql -v ON_ERROR_STOP=1 -X -q -1 -d creddit \
  -f /opt/onchain-credit-staging/scripts/sql/111-pricing-terms.sql

# 3. and 112, which widens the measurement CHECKs 111 created. Same shape, same reasons,
#    and it must not be left for after the deploy: the weekly job writes the new kind from
#    its first run and the database would refuse the INSERT.
sha256sum /opt/onchain-credit-staging/scripts/sql/112-reported-volume-kind.sql  # = your checkout's
sudo -u postgres env "PGOPTIONS=-clock_timeout=10s -cstatement_timeout=300s" \
  psql -v ON_ERROR_STOP=1 -X -q -1 -d creddit \
  -f /opt/onchain-credit-staging/scripts/sql/112-reported-volume-kind.sql

# 4. record BOTH in the ledger, or step 4 of the release order will apply them a second
#    time. The files are idempotent, so a repeat is harmless; a MISSING ledger row is the
#    thing to notice, because it means the ordering this entry argues for did not happen.
sudo -u postgres psql -q -d creddit -c "INSERT INTO onchain_credit.schema_migrations(filename) \
  VALUES ('111-pricing-terms.sql'), ('112-reported-volume-kind.sql') ON CONFLICT DO NOTHING"
sudo -u postgres psql -d creddit -c "SELECT filename, applied_at FROM \
  onchain_credit.schema_migrations WHERE filename IN ('111-pricing-terms.sql', \
  '112-reported-volume-kind.sql')"   # 2 rows
sql
-- Expect: six columns present, the table created, USDD 2.0 seeded, the five moves applied
-- and the two feeds gone. Every one of these is idempotent, so a re-run changes nothing.
SELECT count(*) FROM information_schema.columns
 WHERE table_schema = 'onchain_credit' AND table_name = 'portfolio_tokens'
   AND column_name IN ('mint_terms','redeem_terms','capacity_reader','terms_verified',
                       'loopable','loopable_verified');                        -- 6
SELECT to_regclass('onchain_credit.token_pricing_measurements');               -- not null
SELECT symbol, name, book, feed FROM onchain_credit.portfolio_tokens
 WHERE address IN ('0x4f8e5de400de08b164e7421b3ee387f461becd1a',
                   '0x0c10bf8fcb7bf5412187a595ab97a3609160b5c6');
                                        -- USDD 2.0 (USD, dune_tape) and USDD (legacy)
SELECT symbol, valuation, feed, liquidity FROM onchain_credit.portfolio_tokens
 WHERE address IN ('0x83f20f44975d03b1b09e64809b757c47f942beea',   -- sDAI      composed, NULL
                   '0xa3931d71877c0e7a3148cb7eb4463524fec27fbd',   -- sUSDS     composed, NULL
                   '0x3d7d6fdf07ee548b939a80edbc9b2256d0cdc003',   -- srUSDe    composed, NULL
                   '0xc5d6a7b61d18afa11435a889557b068bb9f29930',   -- sUSDD     composed, NULL
                   '0x056b269eb1f75477a8666ae8c7fe01b64dd55ecc',   -- USD3      market,   dune_tape
                   '0xe1753f2e00940cc31213dd92013cf019dfe4ca1d',   -- sGHO      composed, NULL, secondary
                   '0xc8cf6d7991f15525488b2a83df53468d682ba4b0');  -- sUSDf     composed, NULL, secondary
SELECT count(*) FILTER (WHERE mint_terms IS NOT NULL) AS declared
  FROM onchain_credit.portfolio_tokens WHERE class = 'variable_rate' AND status = 'active';
                       -- 28 of the 46 active variable-rate rows. The other 18 are fund
                       -- shares, which are redemption-priced by definition and declare
                       -- no route.
-- And 112: the measurement vocabulary admits the reported-volume kind, on both CHECKs.
SELECT count(*) FROM pg_constraint
 WHERE conrelid = 'onchain_credit.token_pricing_measurements'::regclass
   AND conname IN ('token_pricing_measurements_kind_chk',
                   'token_pricing_measurements_anchor_chk')
   AND pg_get_constraintdef(oid) LIKE '%reported_median_daily_volume%';          -- 2

No data step follows it, and that is a decision rather than an omission. A redemption-priced row never consults its own bar, so the bars sGHO and sUSDf already hold decide nothing and are left where they are; their sync-state rows are simply never read again once the rows leave the standing set. The four rows that became composed are not re-marked either, because the release deletes every tracked wallet (below) and there is no stored position history for a changed method to restate.

Rollback. An older bundle selects its registry columns by name and never sees the six new ones, has no reason to read a table it does not know about, and can already express every one of the moved rows (composed with an underlying_address, market with a dune_tape feed, and — for sGHO and sUSDf after this file — composed with a NULL feed, which is the shape every fund share already has) — it simply values them the way the previous release decided rather than the way this one does. Nothing is dropped and nothing is deleted, so there is nothing to revert; a genuine reversal is a new migration setting the columns back.

The pricing categories release: prod steps, in order ​

  • belongs to: the pricing categories release (migrations 110, 111 and 112; plan docs/plans/pricing-categories-plan.md) — v0.68.0
  • executed: 2026-09-23

Run end to end on prod 2026-09-23. Step 1 (the two environment variables) 13:06Z; step 2 (111 + 112 by hand) 13:06Z; step 3 (the deploy, merge c667d43d) 13:13Z; step 5 (the wallet wipe) 13:14–13:19Z, 11 accounts and 5 tracked wallets deleted, data-only backup at /root/backup-users-2026-09-23.sql; step 6 (the weekly market measurement added to the crontab and run once) 13:23Z; step 4 (110 by hand, --allow-destructive) 13:24Z; step 7 watched on a hand-run tick at 13:26Z rather than waiting for 50 */6.

The run took 4 last, after 5 and 6, and that is a deviation worth stating rather than tidying away. What this list's ordering is actually load-bearing about held: 111 went on before the deploy, and the environment was set before the first process start. Nothing depends on 110 preceding either of the two steps that overtook it — the wipe leaves no stored history for a purged bar to have marked, and step 6's own constraint is 111, which was seventeen minutes old by then. The cost was the window in step 4's own note: PST and sUSDai read as having no standing feed for eleven minutes rather than for two, and the 13:26Z tick closed it.

5c had to be run twice (13:19Z). The step then deleted the wallet-token coverage rows BEFORE restarting the two processes, and the still-running ingester — holding the enrolled-wallet list it had started with — re-wrote 3 of the 11 rows seconds later, read them back after the restart and resumed backfilling three deleted wallets (enrolled wallets: 3). The step above has since been reordered so the restart comes first; that reordering is what the second pass is evidence for.

This is the running order for the whole release, and the order is load-bearing. Each step links to its own entry where it has one; what this entry adds is the sequence and why nothing may be reordered.

  1. The environment, first, because the first process start after the deploy has to see it./opt/onchain-credit/.env.local on prod needs COINGECKO_API_KEY (the Demo key behind every live price and the hourly history that fills a hole the tape never printed; already set on staging) and DUNE_QUERY_ID_DEX_MARKET=8808795 (the weekly market measurement). The key is not in the repo and never will be. A missing COINGECKO_API_KEY is not an outage — the same host answers keyless at a much lower rate limit and a refused call degrades to DefiLlama and then to the stored bar — but a missing DUNE_QUERY_ID_DEX_MARKET is: without it the trading-day count never arrives and every pricing verdict stays null for ever, which is why the weekly job prints a [fail] line for it rather than a skip.

    Setting the id is not the same as the query being right, because the saved query lives on Dune and no deploy can move it (scripts/dune/README.md: the vendored file is a copy, and changing the file changes nothing). 8808795 has to be at v2, the version that values a trade Dune could not price on its recognised dollar counter leg. At v1 it still answers, still exits zero, and reports USD3 as having traded on 0 of 30 days, which after fourteen days proposes pinning a market-priced asset to its redemption rate. Step 6 is where that is checked, against the data rather than against the id.

  2. Migrations 111 and 112, BY HAND, BEFORE the deploy. Their own entry has the reasoning, the apply and the verification queries. Both are additive, but the standard runner cannot be the way they land here: migrate.sh reads the SQL directory of the checkout it is invoked from, and /opt/onchain-credit does not hold this release's files until step 3 puts them there. Run there now it prints 0 applied and exits 0, which is indistinguishable from "already applied" — and both would then be swept up by step 4, after the deploy, which is the one ordering 111 must not have. They are applied from the staging checkout's copy of the release and recorded in the ledger by hand. 112 widens the measurement CHECKs so the weekly job can write the reported-volume kind; against an unwidened CHECK the database refuses that INSERT from the first run onward.

  3. Deploy the release the ordinary way (merge staging into main; the pipeline restarts the app and the ingester with the new build).

  4. Migration 110, BY HAND, AFTER the deploy. It is tagged -- DESTRUCTIVE and migrate.sh skips it without --allow-destructive. Its own entry has the purge, the two sync-state deletions, the lock_timeout retry note and the verification queries. After the deploy, because between the deploy and this file PST and sUSDai read as having no standing feed at all: nothing is lost permanently, but the shorter the window the fewer hours the next tick has to catch up.

    Read the ledger before running it, because its command is not scoped to 110: 111-pricing-terms.sql and 112-reported-volume-kind.sql must already be listed from step 2. If they are not, step 2 did not happen and this run is what applies them — after the deploy, with every process meanwhile answering from the shipped seed, which is exactly what step 2 is ordered first to avoid.

  5. Delete every tracked wallet. No wallet is repaired and no history is rebuilt: this release changes how four assets are valued and where every live price comes from, so every stored history is a history of a different pricing regime from the one the release reads. Deleting is instant; re-deriving would take hours and produce a history nobody asked for. Run it between 6h ticks (the refresher runs at 50 */6 UTC), as the postgres user, after a data-only backup.

    The restart comes BEFORE the two deletions, and that ordering is the step's one trap. A running ingester keeps writing the wallet-token coverage rows that 5d deletes: its in-flight enrolment backfill re-stamps them as it works. On 2026-09-23, with the deletes run first, three of the eleven rows were back seconds later; the restart then re-read the enrolment list, found those three rows and resumed backfilling three wallets that no longer existed (enrolled wallets: 3), and the delete had to be repeated. Restarting first kills that backfill, so the rows deleted after it stay deleted.

    What the restart does NOT do is drop a list. The ingester re-reads its enrolled wallets every cycle, and that read (WALLET_ENROLMENT_SQL) unions the wallet-token coverage rows themselves — so between 5c and 5d it enrols the eleven wallets from those rows alone, with every account already gone. That is why 5e is read one cycle AFTER 5d and not before it.

    bash
    # PROD. 5a. back up what is about to be deleted. --table-and-children (pg_dump 16),
    #          because -t on a partitioned table dumps the parent, which holds no rows.
    sudo -u postgres pg_dump -d creddit --data-only \
      --table-and-children=onchain_credit.accounts \
      --table-and-children=onchain_credit.account_wallets \
      --table-and-children=onchain_credit.portfolio_position_snapshots \
      --table-and-children=onchain_credit.portfolio_flow_events_v2 \
      > /root/backup-users-$(date +%F).sql
    
    # 5b. the wipe. --execute REQUIRES --confirm-db, matched against current_database().
    sudo -u postgres bash -lc 'cd /opt/onchain-credit && \
      DATABASE_URL="postgres://postgres@/creddit?host=/var/run/postgresql" \
      npx tsx scripts/ops/reset-portfolio-users.ts --execute --confirm-db=creddit'
    
    # 5c. rotate SESSION_SECRET in /opt/onchain-credit/.env.local so no old cookie resolves
    #     to a deleted account, then restart both processes so they pick it up AND so the
    #     in-flight enrolment backfill stops re-stamping the rows 5d is about to delete.
    pm2 restart onchain-credit --update-env
    pm2 restart creddit-event-ingester --update-env
    
    # 5d. the two tables the reset script does not own. AFTER the restart, or the still-running
    #     ingester re-writes the coverage rows it has just had deleted underneath it.
    sudo -u postgres psql -d creddit -c \
      "DELETE FROM onchain_credit.event_coverage WHERE stream = 'wallet-token' AND address <> '*';"
    sudo -u postgres psql -d creddit -c "DELETE FROM onchain_credit.portfolio_held_pts;"
    
    # 5e. confirm the ingester enrolled nothing. WAIT ONE 60s CYCLE after 5d: the line prints
    #     only when the count CHANGES, and the restart's own first read still sees the
    #     coverage rows. The pass is the drop -- `enrolled wallets: 11 -> 0` (whatever N was).
    #     `enrolled wallets: 11` alone is the pre-5d read, not a failure; wait for the arrow.
    #     A count that settles above 0 means 5d landed while something was still writing.
    sleep 70
    pm2 logs creddit-event-ingester --lines 50 --nostream | grep 'enrolled wallets'

    The ingester alarm's feed-lag arm starts paging about 6h later while no wallet is enrolled: with an empty list the wallet-token stream is not emitted, so its cursor stops while its rollout marker stays. The first sign-in clears it.

  6. Add the weekly market measurement to the crontab. It is a manual add, and it must come after 111 because it writes token_pricing_measurements.

    0 5 * * 1 /opt/onchain-credit/scripts/run-cron.sh refresh-token-market.ts
    bash
    # Confirm the line is there and is THIS one, the way the other manual adds are checked.
    crontab -l | grep -c '/opt/onchain-credit/scripts/run-cron.sh refresh-token-market.ts'   # 1
    # And run it once now rather than waiting for Monday.
    /opt/onchain-credit/scripts/run-cron.sh refresh-token-market.ts

    Run it once by hand the same day rather than waiting for Monday: the six-hourly verdict needs the market limb, and until the first run every candidate is null. One Dune execution over every token (about 0.06 credits) plus a pool-reserves walk of a few minutes keyed.

    Then read USD3's row off that first run. It is the check that the saved query on Dune is the v2 this release was measured against (step 1): v1 drops every trade the vendor could not price, and USD3's only venue is a Curve pool against frxUSD where that is all of them.

    bash
    sudo -u postgres psql -d creddit -c \
      "SELECT kind, value_usd FROM onchain_credit.token_pricing_measurements
        WHERE chain_id = 1 AND token_address = '0x056b269eb1f75477a8666ae8c7fe01b64dd55ecc'
          AND kind IN ('dex_trading_days_30d', 'dex_median_daily_volume',
                       'reported_median_daily_volume')
        ORDER BY measured_at DESC, kind LIMIT 3;"

    Expect 30 trading days and two medians in the low hundreds of thousands: the on-chain one read $318,427 on 2026-09-22 and the reported one $315,748 over the 30 days to 2026-09-23, which is the corroboration worth having — two vendors, two methods, the same market. 0 trading days is the v1 answer: fix the saved query on Dune before the fourteen-day hysteresis has anything to count, and the proposal line never appears. No row at all means the Dune limb did not run, which its own [fail] line in the job's output will have said. No reported_median_daily_volume row for ANY token means the volume limb is dark — a spent plan or a refused key — which has its own [fail] line too; every bar then falls back to the on-chain median, which understates a token that trades on exchanges.

  7. Watch the first six-hourly tick (50 */6 UTC) for the lines this release adds. None of them is an outage by itself; they are the signals that say the new machinery is running:

    • [token-pricing] proposal lines, [fail]-prefixed so a run that fails for another reason still quotes them, reporting a token whose category CANDIDATE has disagreed with its declared category for fourteen consecutive days. There can be none on the first tick: the hysteresis needs fourteen days of series. The run still exits zero, and applying a proposal is a registry edit in a pull request, never an automatic flip.
    • [fail] dark feed for a standing feed with no accepted bar in 12 hours, now extended with the sources that were tried. PST is the row to read carefully: it has no CoinGecko listing, DefiLlama prices it, and most of its history will be DefiLlama-filled, which is the accepted outcome of retiring its pool feed rather than a fault.
    • [fail] price disagreement where two vendors disagree beyond the band at the newest hour, and a withheld live price (an M9 dash) for an asset where both were outside it.
    • [fail] the primary vendor answered for NONE of N asset(s), which is the CoinGecko door being shut rather than anything being mispriced: a spent monthly plan, a refused key or a vendor-wide outage. On the FIRST tick after the deploy read it as a key check — step 1 sets COINGECKO_API_KEY, and a box running keyless answers at a much lower rate limit, which is what this line looks like when the variable did not land.
    • [partial] N row(s) have no tape bar in … while the vendors carry them. This one is NOT a failure and is deliberately not a [fail]: the hours were filled and nobody is mispriced. It says the Dune tape has gone quiet for rows the vendors still answer for, which is a question about the saved query's token coverage rather than about the product, and it is expected here for PST.
    • [token-market] limb failures, if the weekly job has been run: one [fail] line per limb that wrote nothing at all, which is what tells a stopped limb from a quiet week. There are three limbs now — the Dune trades, the reported volume, and the pool depth.

What this release does NOT need, said so nobody goes looking for it: no re-mark, no wallet backfill, no history rebuild and no re-derive. The wipe in step 5 is what settles every one of those, and there is no stored position history left for a changed method to restate.

Rollback. Code first: redeploy the previous release. All three migrations are expand/contract and none needs reverting — the older bundle reads an hourly bar and a dune_tape feed exactly as this one does, ignores the six new columns, and values the four moved rows the way it always did. The one thing to watch is 110's own note: a rolled-back process whose registry read FAILS runs its pool leg off the compiled list and writes fresh pool:fluid_dex_t1 bars back into the hours 110 cleared, so a rollback that lasts long enough to matter ends with 110 re-applied.

The ledger-first release: prod steps, in order ​

  • belongs to: the ledger-first release (plan docs/plans/portfolio-ledger-first-plan.md §9 and §10; migrations 114, 115, 116 and 117; sub-PRs S0 #946, S1 #951, S3 #949, S6 #954, S2a #955, S2b #957, S5-lib #956, S4a #958, S4b #959 and S7 #960)
  • executed: 2026-09-26

The whole release is this one entry, and the order is load-bearing. The steps below are §9 of the plan with every sub-PR's server step folded in; the standing procedure each one leans on is in the runbook and is linked from the step. The order differs from §9 in one place, on purpose: the worker starts after the opening backfill (step 6, after steps 4 and 5), where §9 starts it before any backfill. The worker runs the reading audits, and an audit of a wallet enrolled before this release that runs before the wallet's openings exist books each missing opening as an unexplained correction (paged) and opens every unmoved holding a second time at a later reading (S4a's release blocker, plan §10). The opening backfill queues a re-audit that removes both either way, so the order costs pages, not data, but nothing is gained by taking them.

Nothing here is a wipe, a history rebuild or a re-mark, and no stored value is rewritten: the release is expand-only (R13), the old writers keep running beside the new ones for its whole life, and what a user sees moves only in the ways the comparator classes (plan §7.4: rows the ledger holds, a correction's display, dust, the retired W9 / W10 withholds, a value where the frozen one was null, late or corrected series data, and the "Updated" stamp, which S4b's amendment of §7.4 classes by name: the summary's readAt and readBlock and nothing else).

Before step 1: the staging comparison is finished (#960 review round 2, SF-1). Step 1 starts only once the staging order below is done through its step 5 (NEW captured), the plan §7.4 report on the integration PR classifies every difference between OLD and NEW (a difference in no class is a blocker on that PR, and the release waits for its fix), and the crontab restore (its step 6) is done or scheduled. That comparison is this release's approved-diff gate: run after the steps below, it can no longer stop anything.

  1. Migrations 114, 115, 116 and 117, BY HAND, BEFORE the deploy, in that order (all four expand only; none writes a row). The new writers insert the two new kinds (114) and the rate facts (116), and the new loader selects both sets of columns from its first start: after the deploy without 114, the enrolment replay's first opening fails its INSERT and takes the replay's transaction with it, and without 116 every spine write and every page load fails. 115 creates the derivation queue, and 117 restates 115's CHECKs to admit the audit kind, so it must follow it: without it every audit enqueue is refused and no reading is ever audited. The standard runner cannot be the way they land: migrate.sh reads the SQL directory of the checkout it runs from, and /opt/onchain-credit does not hold these files until step 3. The release's copy of the files is the staging checkout's (staging's deploy has applied them to creddit_staging): confirm the commit before trusting it.

    bash
    git -C /opt/onchain-credit-staging rev-parse HEAD                      # = the release PR's head commit
    git -C /opt/onchain-credit-staging status --porcelain -- scripts/sql   # prints nothing: the files are that commit's
    for f in 114-ledger-first-kinds 115-derive-jobs 116-observed-rate-facts 117-audit-job-kind; do
      sudo -u postgres env "PGOPTIONS=-clock_timeout=10s -cstatement_timeout=300s" \
        psql -v ON_ERROR_STOP=1 -X -q -1 -d creddit -f /opt/onchain-credit-staging/scripts/sql/$f.sql \
      && sudo -u postgres psql -q -d creddit -c "INSERT INTO onchain_credit.schema_migrations(filename) \
           VALUES ('$f.sql') ON CONFLICT DO NOTHING" \
      || { echo "STOPPED at $f"; break; }
    done

    Each file is idempotent, so one that aborts on lock_timeout (a live reader held the table) is run again when it is quiet, and the loop resumed from it. Check: SELECT filename FROM onchain_credit.schema_migrations WHERE filename ~ '^11[4-7]-' lists all four; \d onchain_credit.portfolio_flow_events_v2 lists explain_status, cause and reading_block; \d onchain_credit.portfolio_derive_jobs exists and its pdj_kind_chk names audit; \d onchain_credit.portfolio_position_snapshots lists rate_raw and rate_source, and \d onchain_credit.portfolio_pt_prewindow_fills lists consideration_asset, consideration_raw and rate_facts.

  2. The environment: nothing to add. No variable is required by this release. The worker and the producer have tuning knobs that default correctly and stay unset (INGEST_CONTINUOUS_BUDGET_MS, INGEST_CONTINUOUS_POPULATION_TTL_MS, and the alarm's LEDGER_*_MAX_MINUTES bounds, the ingester alarm); LEDGER_WORKER_EXIT_WHEN_IDLE is for a bounded hand-run only and must never be in .env.local, which the pm2 worker sources too.

  3. The deploy (merge staging into main). The pipeline restarts the app, the ingester and, from this release on, the ledger worker (the deploy restarts both). On this deploy there is no worker yet, and that is expected: the restart step prints ::warning::No pm2 process named creddit-ledger-worker, … and the run stays green. Do not start the worker yet (step 6). (A roll-forward: this merge must carry a revert of the revert (roll-forward step 1), and a worker that already exists is stopped BEFORE this step, pm2 stop creddit-ledger-worker && pm2 save, so the deploy leaves it stopped.)

    From here the ingester queues a continuous job for every tracked wallet a cycle sees move, and every stored reading (a page load, Synchronize, the 6h tick) queues an audit job; nothing runs either until step 6, which is intended. The page load, the tick and the enrolment replay keep deriving inline this release (WORKER_OWNS_DERIVATION is false), so nothing a user sees waits on the worker, and a wallet enrolled from now on gets its floor openings from its own replay. What moves at once:

    • the values (the rate facts, 2): every row whose value reads no rate is computed from the first start and takes the bars that landed after its write;
    • the "Updated" stamp: the block time up to which each wallet's movements are derived rather than its newest reading's time (the ingester's first cycle only starts the continuous producer, the cycle after it writes one follow record per wallet it follows, the follow record, and from each wallet's next 6h tick on a quiet wallet's stamp moves every ingester cycle);
    • every holding that never moved inside its history window, for a wallet enrolled before this release: it has no ledger row until step 4, and is off the positions and the All view until then. So take step 4 straight after the deploy.

    Read the ingester's log after its first two cycles: per-stream scanned lines, no cycle error, and no continuous enqueue error (#960 review round 3, SF-2). The continuous producer has no cursor on prod before this deploy (a roll-forward's has one: step 9.1), so its first run only starts it: it logs [ingester/derive-jobs] continuous derivation starts following at block …, queues no job and records no wallet. Every later cycle that ingests new blocks logs [ingester/derive-jobs] J continuous job(s) over [from,to] (J is 0 where no tracked wallet moved), and the first of them ends it with ; now following N more wallet(s), 0 fewer (step 9.1):

    bash
    pm2 logs creddit-event-ingester --lines 50 --nostream | grep -c 'cycle error'                # 0
    pm2 logs creddit-event-ingester --lines 50 --nostream | grep -c 'continuous enqueue error'   # 0

    The hourly alarm pages until step 6. No worker has ever written a heartbeat here, so every freshness run (5 * * * *) from the deploy on prints [fail] ledger-derive-lag: start the worker: pm2 start scripts/worker/run-worker.sh … It has never run here; N job(s) queued and exits 2, which pages (on a roll-forward, whose worker has run before, the line names its last heartbeat instead). That page is this order, not a second fault: N counts the jobs this step and step 4 queue, and the first run after step 6 reads ok. To take no page at all, deploy just after a :05 and reach step 6 before the next one.

    So can the 6h reconciler, until step 4 (PR #961 final review, N4). A reconciler run (30 1,7,13,19 * * *) that falls between this deploy and step 4 reads every wallet enrolled before this release with no openings yet, so a holding whose first in-window record is a movement out of an unstated balance is W6 at its unstated opening, which pages at W6's production budget of zero (P3). That page is this order too, and the next run after step 4 does not repeat it. To take none, deploy and finish step 4 away from those half-hours.

  4. The opening backfill, before the worker starts. One opening per holding each enrolled wallet's floor reading holds, where the ledger has none, a holding worth under a cent included (PR #963, the comparator run's F1: written like any other, and kept off the page while it is dust): dry run by default, insert only, idempotent, one transaction per wallet under the portfolio write lock, and one re-audit queued per wallet it wrote to (what it writes, and why).

    bash
    cd /opt/onchain-credit
    set -a; . ./.env.local; set +a
    # 1. Dry run: one line per opening it would write (wallet, venue, leg, block, the quantity in
    #    its stored count and in the asset's units, its value, its key), one per wallet it skips,
    #    and the summary. Writes nothing.
    npx tsx scripts/ops/backfill-opening-rows.ts --db-url "$DATABASE_URL" | tee /tmp/opening-backfill-dry.log
    # 2. Apply: the same lines, "wrote", and "re-audit queued for <wallet> over [<floor>,<newest>]".
    npx tsx scripts/ops/backfill-opening-rows.ts --db-url "$DATABASE_URL" --apply | tee /tmp/opening-backfill-apply.log
    # 3. Again: it must write nothing ("openings written 0", every row "present, left as is:",
    #    "re-audits queued 0").
    npx tsx scripts/ops/backfill-opening-rows.ts --db-url "$DATABASE_URL" --apply | tail -1

    Record the three summary lines here (opening-backfill: … wallets N (skipped S); openings written W (of which dust, hidden on the surfaces, D), already present P; re-audits queued R). The dry run's to write must equal the apply's written, and its dust count the apply's. D is part of W: every sub-cent floor holding is written, none is left out (the line said dust (no row) D before PR #963, and those holdings got no row). A skipped wallet names why: no derive cursor (its build is in flight or was deferred, and its replay or its audits give it openings) or no stored reading at or after its history floor. Check:

    sql
    SELECT wallet, count(*) AS openings, min(block_number), max(block_number)
      FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND kind = 'opening' GROUP BY wallet ORDER BY wallet;
    SELECT kind, state, count(*) FROM onchain_credit.portfolio_derive_jobs
     WHERE chain_id = 1 GROUP BY 1, 2 ORDER BY 1, 2;
  5. The rate-facts backfill: the rate facts, 3 (a dry run, --apply, and a second --apply that reports 0 write statement(s)). It needs no worker, and the two backfills are independent: this one never touches the audit's rows, which are valued from their readings.

  6. Start the worker (the runbook, which has what healthy looks like). The kill timeout belongs to the process definition, so it is set here, once, and every later deploy's restart keeps it:

    bash
    cd /opt/onchain-credit
    pm2 start scripts/worker/run-worker.sh --name creddit-ledger-worker --time --kill-timeout 120000
    pm2 save
    pm2 logs creddit-ledger-worker

    It drains what steps 3 and 4 queued: the continuous jobs (priority 20), then the audit jobs (25). From here every prod deploy restarts it, and leaves it alone while it is stopped.

  7. PT stamps (#950 review S16, plan §9 (3a)): a PT movement is valued at read from the rate stamped on it at its block (meta.ptRate / meta.ptFactor, since v0.69.0, #940), so a PT movement derived before the stamps is served stored until its wallet is re-derived. Count them, read-only. The count leaves the two audit kinds out: an opening or an adjustment on a PT leg carries no stamp (its meta holds the reading it was written from, or nothing) and is valued from its reading, and a re-derivation keeps every opening, so a count that took them in would name a wallet that held a PT at its floor for good (#960 review B2):

    sql
    SELECT f.wallet, count(*)
      FROM onchain_credit.portfolio_flow_events_v2 f
      JOIN onchain_credit.pendle_markets m ON m.chain_id = f.chain_id AND m.pt_address = f.asset
     WHERE NOT (f.meta ? 'ptRate' OR f.meta ? 'ptFactor')
       AND f.kind NOT IN ('opening', 'adjustment')
     GROUP BY f.wallet;

    Expected: no rows (prod's accounts were enrolled after v0.69.0), and then this step is done. For every wallet it names, enqueue a rederive over the whole window (the hand-insert rules: from_block is the wallet's own floor, and to_block any block at or above the ingested tip, where the writer stops either way; the INSERT below takes the newest block the ingester has scanned), wait for done, and re-run the count, which must return no rows. The jobs are the worker's to run, so this step needs step 6 first. A re-derivation also stamps the re-derived movements' rate facts, keeps every opening and queues the re-audit of the readings it covers.

    sql
    INSERT INTO onchain_credit.portfolio_derive_jobs (chain_id, wallet, from_block, to_block, priority, kind)
    SELECT 1, a.uid,
           CASE WHEN a.history_floor_ts IS NULL OR a.history_floor_block IS NULL THEN 24136053
                ELSE GREATEST(a.history_floor_block, 24136053) END,
           (SELECT max(last_scanned_block) FROM onchain_credit.chain_scan_cursors
             WHERE chain_id = 1 AND scope LIKE 'ledger:%'),
           30, 'rederive'
      FROM onchain_credit.accounts a
     WHERE a.uid IN ('<wallet the count named>', …);

    They are done when SELECT state, count(*) FROM onchain_credit.portfolio_derive_jobs WHERE chain_id = 1 AND kind = 'rederive' GROUP BY 1 shows every one done (a partial one says in its error why it derived nothing: the hand-insert rules).

  8. Crontab: no change this release (R13). The minutely drain and the 6h tick stay, and so does the tick's inline flow pass; the worker's alarm arms ride the existing hourly freshness line. Confirm the three lines are there and are THIS checkout's:

    bash
    crontab -l | grep -c '/opt/onchain-credit/scripts/run-cron.sh drain-portfolio-backfills.ts'   # 1
    crontab -l | grep -c '/opt/onchain-credit/scripts/run-cron.sh refresh-portfolio.ts'           # 1
    crontab -l | grep -c '/opt/onchain-credit/scripts/run-cron.sh check-ingester-freshness.ts'    # 1
  9. Watch, in this order.

    1. The first ingester cycle that sees a tracked wallet move queues a continuous job ([ingester/derive-jobs] … continuous job(s)), and the worker logs -> done for it a few seconds later. The follow records come from the cycle after the deploy's first (step 3: the first only starts the producer), whose line ends now following N more wallet(s), 0 fewer, and SELECT count(*) FROM onchain_credit.chain_scan_cursors WHERE chain_id = 1 AND scope LIKE 'portfolio:derive:v2:1:%:followed-after' is that N (the tick's population). On a roll-forward the producer's cursor is still there from the release's first deploy (neither the old code nor a user wipe touches it), so no cycle starts it: the first one scans on from where the revert stopped it (a stretch more than a day old is left to the 6h sweep, and its line names it), now following counts only the wallets with no record from before the revert, and the count is still the whole population.

    2. The queue drains: the continuous jobs, then the audit jobs. Once it has:

      bash
      pm2 logs creddit-ledger-worker --lines 5000 --nostream | grep -E 'job #[0-9]+ audit ' \
        | grep -oE -- '-> (done|partial|queued|failed)' | sort | uniq -c
      pm2 logs creddit-ledger-worker --lines 5000 --nostream | grep '\[ledger-audit\]'
      cd /opt/onchain-credit && ./scripts/run-cron.sh check-ingester-freshness.ts
      grep 'env=onchain-credit$' /tmp/onchain-credit-cron/onchain-credit-check-ingester-freshness.log | tail -4
      sql
      SELECT kind, explain_status, count(*), count(DISTINCT wallet) AS wallets
        FROM onchain_credit.portfolio_flow_events_v2
       WHERE chain_id = 1 AND kind IN ('opening', 'adjustment')
       GROUP BY 1, 2 ORDER BY 1, 2;

      Expected: every audit job done (a queued retry while a wallet's ledger catches up to its reading is healthy and spends no attempt), the freshness run's four ok lines (freshness, feed lag, derive lag, ledger audit), the openings step 4 wrote plus any a new enrolment wrote itself, and no unexplained adjustment (an accepted one, a native ether transfer, is fine and pages nothing). An unexplained one is a real finding: the worker's [ledger-audit] line names the wallet, venue, leg, block range and size, and the remedy is the ledger audit arm's (the runbook). Record the counts here. An audit job that ends failed (three attempts that threw) is not closed by the worker, and the derive-lag arm pages it hourly until somebody deals with it: read its error, then requeue it or close it as the runbook says (S4a).

      One cause of an unexplained correction is known and has no decoder yet: a WETH wrap or unwrap. A tracked wallet's own deposit() or withdraw() on WETH9 emits Deposit or Withdrawal and never a Transfer, and no stream ingests either event. So from this release each one books an unexplained WETH correction at the wallet's next reading: a page, a "Balance adjustment ±X WETH, cause under review" line on the activity statement, and the stretch up to that reading not measured; its ether side is an accepted native-ether correction. Its cause reads … log(s) found, … on no ingested stream, never no chain evidence: the explanation found the wrap and cannot book it. This is #956's F1, still open as Fred's decision (the contract release). For one of these, record the wallet and the transaction here and take no other step.

    3. The worker's first day (its health check): the page load's skipped merges (grep -c 'writer lock busy; v2 persist skipped' /root/.pm2/logs/onchain-credit-out.log, a handful a day, compared with the same window before the deploy); the worker's verdicts, mostly -> done and no -> failed (a -> queued naming another writer is the stale-merge fence and is healthy when occasional); no continuous enqueue error; at most one open continuous job per wallet (the worker's health check).

    4. Synchronize on a tracked wallet (Fred's): the response says refreshed: true (or refreshed: false with skippedReason: "nothing-newer" in the ~13 minutes after a 6h tick, when there is nothing newer to read), and the summary's readBlock is at or above the live tip it stored, unless the wallet still owes an earlier stretch: its pending marker, which SELECT last_scanned_block FROM onchain_credit.chain_scan_cursors WHERE chain_id = 1 AND scope = 'portfolio:derive:v2:1:<wallet, lowercase>:jit-pending' returns when there is one. A page load's reading counts only below that marker (#959 review round 4, B3), so readBlock can stay below the tip it just stored until the next 6h tick, or the wallet's next continuous job, derives the stretch. readAt is readBlock's own time on any explorer.

    5. The first 6h tick after the start (50 */6): its audit jobs done within minutes and no unexplained correction on a clean wallet; from then on a quiet wallet's summary readBlock follows the ingester, a minute or two behind the chain (one that owes a stretch, as in 4, once that stretch is derived).

    6. The first 6h reconciler run after the start (30 1,7,13,19): its values= line (the rate facts, 5): differ above zero is expected, factless=r/m/f is recorded here.

  10. The node provider's key: Fred decides (#954 follow-up 1, its second half; #960 review round 2, SF-4). This step is Fred's decision, not the operator's: record what he decided here, and take only that. From step 3 the ingester's start line redacts its endpoints, but every ingester start before it printed the live and archive RPC URLs whole, key included, into /root/.pm2/logs/creddit-event-ingester-out.log. The reference log rotation does not cover that file (log rotation), so unless the box's copy was extended, every such line since the ingester's first start is still in it. The S6 window's staging hand-run logs (/tmp/staging-ingester-2026-09-24T*-s6.log) held the key too; #954 redacted them in place and set them to 0600 (plan §10), so check them rather than assume. Count the lines that hold the archive URL, key included, without printing it (the same with ETHEREUM_RPC_URL where that URL carries a key):

    bash
    (cd /opt/onchain-credit && set -a && . ./.env.local && set +a && test -n "$ETHEREUM_ARCHIVE_RPC_URL" && \
      zgrep -c -F -e "$ETHEREUM_ARCHIVE_RPC_URL" /root/.pm2/logs/creddit-event-ingester-out.log*)
    (cd /opt/onchain-credit-staging && set -a && . ./.env.local && set +a && test -n "$ETHEREUM_ARCHIVE_RPC_URL" && \
      grep -c -F -e "$ETHEREUM_ARCHIVE_RPC_URL" /tmp/staging-ingester-2026-09-24T*-s6.log)

    The remedies, either or both:

    • Rotate the key at the provider, put the new one in /opt/onchain-credit/.env.local (and in staging's, where it is the same key), and restart what read the old one: pm2 restart onchain-credit --update-env, the ingester and the worker (restart by hand), and onchain-credit-staging if staging's file changed; the crons read the file on each run. A rotated key makes every copy on disk worthless.
    • Empty the log: truncate -s 0 /root/.pm2/logs/creddit-event-ingester-out.log (pm2 appends, so the ingester goes on writing to the emptied file), and delete any rotated copy the count named. The ingester's log from before this release goes with it.

    On a roll-forward the step applies again: the reverted code's ingester printed the key in use at its start during the revert.

  11. Record every step's summary lines in this entry, and set executed: to the date. The same follow-up PR sets the plan's header (docs/plans/portfolio-ledger-first-plan.md, PR #961 final review B2) to status: built-with-deviations, with landed: naming the release version and current: naming the deviations: the worker started after the backfills, R2's never-read leg (a leg the chain holds that no reading has read is served nowhere, §11), and the decision still open with Fred on incoming ether in the fold (§11); then cd docs && npm run plans:index.

Executed 2026-09-26 (Fred: "Go no need to rotate the key"), summary lines per step.

  1. Migrations 114–117 applied by hand from /opt/onchain-credit-staging at c0ac76b6 (14:0xZ); all four in schema_migrations; every column and the pdj_kind_chk check present.
  2. No environment change.
  3. Release PR #964 merged; deploy.yml run 36247157828 green; prod head 5e3923df (v0.71.0); ingester restarted 14:03:42Z, continuous derivation starts following at block 26062036, next cycle now following 5 more wallet(s), 0 fewer; 0 cycle error, 0 continuous enqueue error.
  4. opening-backfill: APPLIED; wallets 4 (skipped 0); openings written 63 (of which dust, hidden on the surfaces, 2), already present 0; re-audits queued 4; re-run: written 0, already present 63, re-audits queued 0 (0xd775 43, 0xe51d 15, 0xea88 4, 0xef08 1).
  5. rate-facts: APPLIED; readings: scanned 2594, lacking a fact 455, filled 455 (facts: 455 chain); movements: scanned 168, lacking a fact 7, filled 7; pre-window fills: scanned 6, lacking a fact 6, filled 6; 141 chain read(s), 12 write statement(s); re-run 0 write statement(s).
  6. Worker started 14:05:18Z (creddit-ledger-worker, kill timeout 120000, pm2 save); the 4 continuous jobs done; audits #1 done (0 booked), #3 done (2 accepted), #2 and #4 partial (8 + 3 accepted; wallet-token legs unread at two past readings, no page).
  7. PT-stamp count: no rows.
  8. Crontab lines 1 / 1 / 1.
  9. Freshness arms (direct run, 14:0xZ): ingester ok, feed-lag ok, ledger-derive-lag ok (heartbeat, 0 queued, 2 partial in 24h), ledger-audit ok (no unexplained adjustment, no leg unread twice). Ticks 18:00Z, 00:00Z, 06:00Z, 12:00Z wrote their checkpoints; by 2026-09-27 16:30Z: 18 audits done, 3 partial, 27 continuous done, 20 accepted native-eth-transfer corrections, 0 unexplained. Fred's wallet 0xe159…6b0b enrolled 19:21Z, replay done, its page-load reading at block 26063745 audited done. The "Updated" stamp trails the chain by the ingester's 64-block finality margin (~13 min): issue #965 (serve the tip, pending finality).
  10. Key rotation: Fred decided NOT to rotate (2026-09-26).
  11. This record. Staging's reseed pause (/root/.reseed-paused) removed 14:1xZ.

The rate facts: migration 116 and its backfill ​

From this release the money columns are computed at read from each row's facts, and a row whose value reads a rate no fact answers is served its stored columns (the loader rule). These steps (S2b) take the environment from "every rate-reading row served stored" to "every row computed that a fact can compute"; the list above says where each one falls in the release's order.

  1. Migration 116, before the deploy (step 1 applies it with the other three). Expand only: nullable columns and two CHECKs, and it writes no row. The new writers insert into the columns and the new loader selects them from its first start, so a deploy that lands before 116 fails every spine write and every page load until it is applied.

  2. What the deploy moves (step 3). From here every new reading, movement and fill carries its facts. What a user sees moves at once in three places, all of them the served number catching up with the price series (plan §7.4 d1), none of them a rate:

    • A row whose value reads NO rate is computed from the first start, written before 116 or not: every par, identity and excluded leg (USDC, USDT, DAI, GHO, WETH, WBTC, XAUt, …) and every movement priced from bars alone. Such a row now takes the bar covering its own moment, so it moves wherever a bar landed after its write or was corrected since (the 6h tick prices with the bars the last sync had written, routinely hours old). A live tip written before this release that stored a vendor level where no bar stood is valued from the bars (or "not measured" where none stands) until the next tick supersedes it.
    • A row whose value reads a rate, written before 116, is served stored: what it served before the release.
    • So a wrapper leg's history mixes the two where its last stored reading meets its first computed one: the return over that interval carries the difference between the bar its stored value was struck at and the covering bar, until the backfill (3) computes the older rows too. A row the backfill cannot fill keeps that seam.
  3. The rate-facts backfill (step 5; the runbook): a dry run, then --apply, then a second --apply that must report 0 write statement(s). Record each run's summary line here, with the rows it left and why. It fills a fact (the chain's answer at the row's block, or the fallback its writer had) only where the served read then reproduces the stored value of every row the fact turns computed: the row it fills, and every other leg of the same reading that reads the same rate, since the read pools a reading's facts over its legs (review S8 of #957). Where one of those legs does not reproduce, that rate is filled nowhere in the reading. So every row the backfill turns computed serves what it served before, up to late or corrected series data or a hole it fills, and every row it leaves is served exactly as before (a row written before 116 that no fact reaches stays served stored). The summary counts apart, as computed through another leg's fact, the legs it does not fill that the read computes through a fact another leg of their reading holds (typically a PT leg over a composed payout asset); they are not among the rows left.

    bash
    cd /opt/onchain-credit
    set -a; . ./.env.local; set +a
    npx tsx scripts/ops/backfill-rate-facts.ts --db-url "$DATABASE_URL" | tee /tmp/rate-facts-dry.log
    npx tsx scripts/ops/backfill-rate-facts.ts --db-url "$DATABASE_URL" --apply | tee /tmp/rate-facts-apply.log
    npx tsx scripts/ops/backfill-rate-facts.ts --db-url "$DATABASE_URL" --apply | tail -1   # 0 write statement(s)
  4. PT stamps (step 7): a PT movement derived before v0.69.0's stamps is served stored until its wallet is re-derived; a re-derivation also stamps the re-derived movements' rate facts.

  5. The check (step 9). The next 6h reconciler run prints, per wallet and summed, differ= and factless=r/m/f on its values= line (the acceptance reconciler). Expect differ above zero: it counts the computed rows whose value moved off the stored one by a bar that landed or was corrected after the write (2), and scripts/ops/value-parity.ts --db-url … classes every such line as late or corrected series data; a line it leaves as RESIDUE is the finding to chase. factless is what is still served stored: the rows the backfill left (its summary says why), a PT movement with no stamp (4), and the two classes the writers keep producing that no fact column holds (a reading over wFalconX-style two-level compositions, a PT leg over a composed payout asset: the loader rule). Record the numbers here. The contract release that drops value_market / value_redemption requires 0/0/0, so it owes a decision on those two classes first (below).

Rollback, and a roll-forward after it ​

Rollback.

  1. Stop the worker first: pm2 stop creddit-ledger-worker && pm2 save. It runs this release's code, and once the release is reverted nothing it would still do is wanted (the old code produces no job and never reads the queue). Stopped before the revert, it writes nothing over the old code's rows in the minutes the revert takes to deploy. Until the revert's deploy lands, the hourly freshness check is still this release's, so every run (:05) more than ten minutes after the stop pages for the stale heartbeat until then: once, for a revert that lands within the hour. That page is this step; the old check has no worker arm.

  2. Revert the release commit on main. The release landed as its release PR's merge commit (the Merge pull request #… from FredCoen/release/… that shipped it, in git log --first-parent origin/main): revert it with git revert -m 1 <that commit> on a branch off main, and merge that as a PR into main. The revert's own deploy runs the workflow as it stood before this release: it restarts the app and the ingester on the old code, and does not know the worker, which stays stopped. Keep the revert off staging while a roll-forward is intended: back-merged alone (the runbook's hotfix rule), it would take the release out of staging's next deploy too, and a roll-forward brings it back only with a revert of the revert (roll-forward step 1).

  3. Delete the two new kinds as soon as the revert's deploy is green, before the next 6h tick (50 */6) or reconciler run (30 1,7,13,19). Not optional: the old loader counts opening and adjustment rows and skips them, but three other parts of the old code do not tolerate them (#960 review B1):

    • The events list fails. /api/portfolio/events reads every kind of a wallet's ledger and throws on a kind outside its twelve, so it answers 500 ("Could not load events.") for any page that holds an opening or an adjustment: a wallet's last page, since its floor openings are its oldest rows, and every page of a wallet whose ledger is all openings (in the staging population, 0xd775, whose 43 legs never moved, fails on its first).
    • The 6h tick refuses its merges and pages [partial] every 6h. The old range merge requires its wallet-token universe to hold every asset its range's stored wallet-leg rows name, and it counts rows of every kind, while that universe holds only tokens a Transfer moved in the range (it has no held-now term). An opening or a correction on a wallet leg nothing moved in the range falls outside it: the merge refuses (unresolvable-universe) and marks the range pending, and the same row refuses the range again at every later tick and page load, so it never clears. The routine case is the accepted native-ether correction: gas moves native ether without a log, so every wallet that transacts has them, and each sits at a reading block above the tick cursor (the tick derives to 64 blocks below the block it reads at). This release's copy of the check leaves the two kinds out (S4a); the old code's does not.
    • The reconciler pages P4. It carries a kind it does not know through to its reducer on purpose, so a window the old engine booked with an opening or an adjustment inside it reports completeness none ([fail] ledger-reconcile unexplained, exit 2).

    The old code writes neither kind, so nothing re-creates them once they are gone. Record the per-wallet counts here first (the roll-forward reads them), then delete, then check:

    sql
    SELECT wallet, kind, explain_status, count(*)
      FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND kind IN ('opening', 'adjustment')
     GROUP BY 1, 2, 3 ORDER BY 1, 2, 3;
    DELETE FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND kind IN ('opening', 'adjustment');
    SELECT count(*) FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND kind IN ('opening', 'adjustment');   -- 0

    A range a page load's merge refused between the deploy and the delete is marked pending, and the next tick derives it, now that nothing refuses it.

  4. No migration is rolled back. All four are expand only, and the old code never names their columns. The queue is left as it stands: the old code never reads it.

A roll-forward after it.

  1. Bring the release back with a revert of the revert (#960 review round 3, SF-1). Once main holds rollback step 2's revert, git treats the release's commits as merged: a later merge of staging, or of a branch cut from it, brings only what was committed since, never what the revert took out. Step 3 as written (a release PR from staging) would ship the old code with any fix on top, release.yml would tag that with the bumped version, and step 4 would fail, its tool not being on main. So the roll-forward's merge carries a revert of the revert, one of two ways:

    • On a branch off main: git revert <the commit rollback step 2 made>, or git revert -m 1 <the revert PR's merge commit>, then git merge origin/staging when the roll-forward carries a fix made on staging, opened as a PR into main, whose merge is step 3's deploy. Afterwards bring staging level with main: git push origin origin/main:staging, or, where staging has moved on, a PR merging main into it.
    • On staging, then the usual release PR: on a branch off staging, git merge origin/main (the revert, which takes the release out of the branch) and then the same git revert (which puts it back), merged into staging as one PR. Staging's code does not change, and its history now holds the revert and its revert, so step 3's release PR from staging carries the release again. Take this way before a fix to the release's own files lands on staging: after that, the back-merge meets the fix as a conflict (a file the revert deletes and the fix changes), and the first way is the one that works.

    Either way staging ends up carrying the release again, as it must: the next release PR ships from it.

    A fix the roll-forward carries that moves a served number takes the precondition again (before step 1): the plan §7.4 report is re-run over the surfaces the fix changes, with NEW captured with the fix (plan §7.3), every difference is classed on the fix's PR, and step 3 waits for it; a difference in no class blocks the roll-forward as it blocked the release. A fix that moves none (its goldens byte-identical, plan §6) keeps the report the release was approved on.

  2. Clear the rate facts the revert made stale. The old code re-reads a reading at an existing label (the 6h tick's same-window re-read) and upserts its new values, block and updated_at, but keeps the fact of the earlier read, from which the new code would compute. So before the roll-forward's deploy, clear the facts of every reading written during the revert; step 5 fills them again where their stored values reproduce:

    sql
    UPDATE onchain_credit.portfolio_position_snapshots
       SET rate_raw = NULL, rate_source = NULL
     WHERE chain_id = 1 AND updated_at >= '<the revert deploy, UTC>' AND rate_raw IS NOT NULL;

    A movement the old code re-derived is rewritten with its whole meta, which drops its facts: it is served stored until the backfill fills it, and needs nothing by hand.

  3. Take steps 3 to 11 again, with the worker stopped until step 6. The deploy leaves a stopped worker stopped. The opening backfill (step 4) writes only what is missing, so it restores every opening rollback step 3 deleted, and the full-window re-audit it queues for each wallet it writes to is what books the corrections again, at the readings that found them. An unexplained one is a new row then, so the ledger audit arm pages for it again: expect that for every unexplained count the rollback recorded. A wallet it writes nothing to (its floor reading holds nothing) gets no re-audit: for every wallet the counts recorded at rollback step 3 name and the apply's log names in no [backfill-opening-rows] re-audit line, enqueue a whole-window rederive (step 7's INSERT) before step 6. A re-derivation queues the re-audit of the readings it covers, which books that wallet's corrections again. What the queue kept from before the revert drains with the rest: a continuous job starts at its wallet's tick floor as it stands when it runs, and an audit past its six-hour horizon ends partial by itself. Except the jobs of a wallet deleted during the revert: that delete went through the old tool and runbook, which do not know the queue, and a job left for a wallet no account holds fails on the ledger's foreign key and pages once the worker starts. So before step 6, delete them (the user wipe's own statement):

    sql
    DELETE FROM onchain_credit.portfolio_derive_jobs j
     WHERE NOT EXISTS (SELECT 1 FROM onchain_credit.accounts a WHERE a.uid = j.wallet);

Staging: the order before the comparator's NEW capture ​

The comparator's window on staging (plan §7.3, S6 preparation #954) is open until the NEW capture, and its rules and state are recorded in plan §10, where each step below is logged when it runs. Staging runs no ingester and no worker, so nothing there drains the queue by itself. The prod steps above wait for this order (their precondition).

One hand-run at a time, each with a small pool. Steps 2 to 4 are hand-runs against creddit_staging, whose role is capped at 20 connections. In the S6 window seven runs that overlapped a hand-run ingester cycle and the minutely drain failed on that cap (too many connections for role "onchain_credit_staging") and sent seven cron-failure pages (#954 follow-up 3). So run each step alone, never beside another hand-run, and with PG_POOL_MAX=4 in its environment (the cap the deploy's build uses), which bounds the shared pool a run opens beside its own connections.

Staging's own commands, never prod's (#960 review round 2, SF-2). Steps 2 to 4 run from the staging checkout, with staging's environment, over the population alone, and no command in them names pm2. Prod's worker runs from /opt/onchain-credit on the same box, so the prod steps' commands copied here (cd /opt/onchain-credit, its .env.local, and the pm2 stop / pm2 start around a worker hand-run) would stop prod's worker and drain prod's queue. Each of the three steps runs in a shell set up like this, its checks first:

bash
cd /opt/onchain-credit-staging
set -a; . ./.env.local; set +a
printf '%s\n' "$DATABASE_URL" | grep -c '/creddit_staging'   # 1: this shell writes staging's database
grep -c PG_POOL_MAX .env.local                              # 0: run-worker.sh sources .env.local AFTER the
                                                            #    command line, so a value there would win
W=$(node -p 'require("./tests/comparator/old/manifest.json").wallets.join(",")')
echo "$W" | tr ',' '\n' | grep -c '^0x[0-9a-f]\{40\}$'       # 12: the population, from OLD's manifest
umask 077                                                   # the logs below are readable by root alone
  1. Deploy the integration branch to staging, schema only. Its migrations (114, 115, 116 and 117) add columns, a table and CHECKs, and write no row; the staging deploy applies them through migrate.sh. A file that writes rows waits until NEW is captured.

  2. The rate-facts backfill of the population (the rate facts, 3): the 3,336 readings and 225 receipts, in place, at each row's own block. One of the window's two row-writing exceptions: it writes the fact columns only and leaves updated_at alone, so NEW's readings digests stay equal.

    bash
    date -u
    PG_POOL_MAX=4 npx tsx scripts/ops/backfill-rate-facts.ts --db-url "$DATABASE_URL" --wallets "$W" | tee /tmp/staging-rate-facts-dry.log
    PG_POOL_MAX=4 npx tsx scripts/ops/backfill-rate-facts.ts --db-url "$DATABASE_URL" --wallets "$W" --apply | tee /tmp/staging-rate-facts-apply.log
    PG_POOL_MAX=4 npx tsx scripts/ops/backfill-rate-facts.ts --db-url "$DATABASE_URL" --wallets "$W" --apply | tail -1   # 0 write statement(s)
    date -u

    Check: the apply fills what the dry run said it would, and its summary lists the rows it left and why; the second apply reports 0 write statement(s). Log in plan §10 the commands, the start and end, and the three summary lines.

  3. The opening backfill of the population (the tool of prod step 4): the other exception, which S4a's follow-up 1 added to the window's order. S4a's release blocker applies to NEW as it does to prod (without it, a population wallet's holdings that never moved are off NEW's surfaces), and the openings come from each wallet's stored floor reading, never from a new replay. It writes opening rows and queues one re-audit per wallet it wrote to; NEW's pin check reports the ledger rows' counts and digests as moved, which step 5 expects.

    bash
    date -u
    PG_POOL_MAX=4 npx tsx scripts/ops/backfill-opening-rows.ts --db-url "$DATABASE_URL" --wallets "$W" | tee /tmp/staging-opening-backfill-dry.log
    PG_POOL_MAX=4 npx tsx scripts/ops/backfill-opening-rows.ts --db-url "$DATABASE_URL" --wallets "$W" --apply | tee /tmp/staging-opening-backfill-apply.log
    PG_POOL_MAX=4 npx tsx scripts/ops/backfill-opening-rows.ts --db-url "$DATABASE_URL" --wallets "$W" --apply | tail -1
    date -u
    sudo -u postgres psql -d creddit_staging -c "SELECT wallet, count(*) AS openings FROM onchain_credit.portfolio_flow_events_v2 WHERE chain_id = 1 AND kind = 'opening' GROUP BY wallet ORDER BY wallet"

    Check: the dry run's to write equals the apply's written, and the apply logs one re-audit queued for <wallet> … line per wallet it wrote to; the second apply writes nothing (openings written 0, re-audits queued 0); 0xd775, whose 43 legs never moved, now holds 43 openings (its 1e-7 WETH included). On a re-run over the state the 2026-09-26 run left (its 97 openings in place, the population not reseeded): the dry run and the apply write the floor's sub-cent holdings that run left unopened (its dry run said dust (no row) 7; now openings written 7 (of which dust, hidden on the surfaces, 7), already present 97) and queue one re-audit per wallet written to. Step 4's drain runs those re-audits: 0x53e2's REMOVES the +0.0001 USDT correction the first run's audit booked (… reading @25857182: … 1 removed) and pages nothing, and the others are expected to book nothing (a dust leg that grew with no recorded movement would be a break, explained first, and is named in the job's reason if one does). Log it in plan §10 as for step 2.

  4. rederive the 12 wallets (§7.3), then drain the queue: the re-derivations, and the audits that step 3 and the re-derivations queued. The INSERT is prod step 7's, over the population and against creddit_staging (psql prints INSERT 0 12):

    bash
    sudo -u postgres psql -d creddit_staging -v ON_ERROR_STOP=1 -c "
      INSERT INTO onchain_credit.portfolio_derive_jobs (chain_id, wallet, from_block, to_block, priority, kind)
      SELECT 1, a.uid,
             CASE WHEN a.history_floor_ts IS NULL OR a.history_floor_block IS NULL THEN 24136053
                  ELSE GREATEST(a.history_floor_block, 24136053) END,
             (SELECT max(last_scanned_block) FROM onchain_credit.chain_scan_cursors
               WHERE chain_id = 1 AND scope LIKE 'ledger:%'),
             30, 'rederive'
        FROM onchain_credit.accounts a
       WHERE a.uid = ANY ('{$W}'::text[])"

    Then the queue, and a bounded worker hand-run with no pm2:

    bash
    sudo -u postgres psql -d creddit_staging -c "SELECT wallet = ANY ('{$W}'::text[]) AS population, kind, state, count(*) FROM onchain_credit.portfolio_derive_jobs WHERE chain_id = 1 GROUP BY 1, 2, 3 ORDER BY 1, 2, 3"
    PG_POOL_MAX=4 LEDGER_WORKER_EXIT_WHEN_IDLE=1 bash scripts/worker/run-worker.sh 2>&1 | tee -a /tmp/staging-worker-s7.log

    Before the first hand-run every row of the query is population = t (a job of another wallet was queued outside this order: find out why before draining). Repeat both, a minute apart, until the query shows no queued and no running row: the hand-run exits once nothing is claimable, and a job sent back (an audit waiting for an earlier reading's audit, say) is claimable again only after its backoff. The hand-run's worker lock is taken in creddit_staging, where nothing else holds one (prod's worker holds its own in creddit), so it neither waits for prod's worker nor stops it. Check: every rederive ends done, and grep -c -- '-> failed' /tmp/staging-worker-s7.log prints 0. Log the job counts in plan §10.

  5. Capture NEW: npx tsx scripts/ops/golden-portfolio.ts --db-url … --pin-from tests/comparator/old/manifest.json --label "NEW …" --out tests/comparator/new. It refuses if a wallet's newest reading moved (--override records it) and reports every mark that moved. Expected to move: both tables' column lists (the new columns), the ledger rows' counts and digests (the receipts' rate facts, rederive, the opening rows) and the derive cursors. A readings digest that moved means a stored reading was rewritten, and §7.4 must explain it.

  6. Restore the crontab: all three PAUSED-S6 lines at once, from a file and never through a pipe (in crontab -l | sed … | crontab -, a failing crontab -l installs an EMPTY crontab, prod lines included). Verbatim from #954:

    bash
    ts=$(date -u +%Y%m%dT%H%M%SZ)
    crontab -l > /root/crontab.pre-restore-s6-$ts && test -s /root/crontab.pre-restore-s6-$ts
    sed 's/^# PAUSED-S6 2026-09-24 ([^)]*) //' /root/crontab.pre-restore-s6-$ts > /root/crontab.restore-s6-$ts
    test -s /root/crontab.restore-s6-$ts && diff /root/crontab.pre-restore-s6-$ts /root/crontab.restore-s6-$ts
    # the diff must show exactly the three PAUSED-S6 lines losing the marker, and nothing else
    crontab /root/crontab.restore-s6-$ts && crontab -l | diff - /root/crontab.restore-s6-$ts && echo restored

    The dry run on 2026-09-24 21:36Z proved it exact: the marker stripped from the live crontab reproduced /root/crontab.bak-s6-20260924T195921Z, the crontab from before the window, byte for byte. The next nightly reseed then removes the hand-inserted wallet-token rollout marker again (plan §10); whether the scrub should keep it is carried in plan §11 (#954 follow-up 2).

    What the restore turns back on (#960 review round 2, N4): the 03:00 reseed, which restores prod's schema and runs no migrate.sh. Until the release's step 1, prod's schema lacks 114 to 117, so from that reseed until one restores a dump that has them, or a staging redeploy applies them, every spine write and page load of staging's app fails. So release before the next reseed, or redeploy staging after it.

The contract release: what this one leaves for the next ​

This release is expand only (R13): the old writers run beside the new ones, the stored value columns stay filled, and nothing the old code needs is removed. The contract release after it, once the audits have run clean for a week (§9), takes these, each its own reviewed change and, where it touches prod data, its own entry in this log:

  • Drop value_market / value_redemption from the readings (DESTRUCTIVE, -- DESTRUCTIVE, hand-run): taken by the contract release, step 2 (migration 129, run on prod 2026-10-04 in v0.76.0). Only once the reconciler's factless=0/0/0 across the population, which first needed a decision (Fred's) on the two classes the writers kept producing that no fact column held: a reading over a two-level chain-rated composition, and a PT leg over a composed payout asset (the loader rule; PT-fxSAVE-29OCT2026 over f(x)'s pool share is one from migration 126, its entry). Decided 2026-10-02 and built by migration 128 (its entry): a reading keeps every rate its value read, so a PT-fxSAVE reading written after it computes from its own facts.
  • Flip WORKER_OWNS_DERIVATION (taken by the contract release, step 1; the inline paths and the constant deleted by step 2, v0.76.0, 2026-10-04): the page load, the registration replay and the 6h tick become enqueue-only (sync, enrol, sweep), and the worker is the only derivation writer besides the offline history builder. The flip's own gates, from #949:
    • the stale-merge fence's four Postgres cases (round-6 SF-1): a row rewritten in place, a row deleted, a delete and an insert in one transaction, and the identical re-upsert as the control, each through the fence on a fixture clone. Today's cases all insert, so a fence that compared the row count alone would pass them;
    • a hand-typed sync or enrol row (SF-A, carried follow-up 9): handMadeKindRefusal returns null once the constant flips, so the flip has to tell a producer's row from a typed one (a producer-stamped column the kind's CHECK requires, or each kind re-checking its producer's guard when it runs);
    • the fence stays on every tick-range kind, sweep and sync included (true today, pinned); the re-derivation trigger moves onto rederive jobs (carried 1); a completed sweep notes its scanned scope (carried 2); the [partial] paging contract carries onto partial jobs (carried 4); failed sweep jobs fold into one standing row as continuous ones do; sync jobs are deduplicated per wallet (F1); settleSweep counts only the jobs still in the table (F2); and a chronically partial wallet holding the tick cursor is a decision for Fred (S8c);
    • one lane (carried 8, a decision for the flip): a sync job waits behind a running whole-window enrol, so once the page load's derivation is a sync job, a page load during a large wallet's enrolment times out to derivation-pending. A second lane for sync, or sync claimed between an enrolment's chunks;
    • the per-job reads, measured again at the flip's volume (carried 7): every job re-reads the scope registries, the rolled-out set, the ingested tip and, when it inserted legs, the PT universe, and the fence adds its two fingerprint reads (about 32 ms on a 100,000-row wallet, round-6 N1). A short per-loop cache is the easy win; a per-wallet ledger version that every writer bumps is the fence's constant-time form;
    • base defect 5's mirrored order stays open for the history builder. A whole-window merge re-derives only through the tip it read when it began, so rows a tick-range merge commits above that tip meanwhile keep their old anchors, below the tick cursor. Carried 1 closes it for the population's tick; the offline history builder stays a direct writer after the flip, so a history build keeps the order open until it too runs through the worker;
    • round 5's two nits: the SF-B fixture recipe gains the head-bound case (to_block the chain head with the arm above the ingested tip, which only the tip guard catches), and historyVerdict's empty-range reason stops saying "deferred" for a rederive (only an enrol writes the deferral marker): it says the job derived nothing and when to enqueue it again;
    • the deploy's restart turns a missing worker into a red run by itself: restart-ingester.sh reads the constant from the checkout it deploys. Until the worker restarts on the flip's deploy, an old-code worker refuses the new page load's sync jobs (partial, so refreshed: false), for the minute or two the restarts take. Restarting the worker before the app on that one deploy closes it.
    • Where each landed (the contract release, step 1): the fence's four cases are pinned on a fixture clone; a typed row is refused by a producer stamp that migration 122's CHECK requires (on sweep too, whose typed row would move the tick cursor for everyone); of the gates above called true today only the fence on every tick-range kind held, and carried 1, 2 and 4, the failed-sweep row, F1 and F2 were built and pinned there; one lane became a second lane for sync; the reads were measured and left uncached; round 5's two nits are in; and the deploy order is a hand step, the worker stopped across the flip's deploy (a restart before the app narrows the window and does not close it). S8c stays Fred's decision, on that entry's watch list, and so does the history builder's mirrored order.
  • Capacity and the soak, before an outside cohort (#949's later waves; fine at today's population): an old pending marker widens every continuous job for its wallet (a job starts at its wallet's pending marker when that is below the tick cursor); NAMED_ADDRESSES_SQL binds the whole population as one parameter every cycle; and the worker soak runs no whole-window writer (the fence's fixture cases pin that class; an inline replay or trigger merge fired at random in the soak would cover its interleavings).
  • Retire the minutely drain line and the tick's inline flow pass (§9, R13): after the flip the drain's derivation and the tick's are the worker's enrol and sweep jobs, so the crontab's * * * * * … drain-portfolio-backfills.ts line and the tick's own flow pass go, once whatever else the drain still runs (the registration replay's spine half, the re-derivation trigger until it is a rederive producer) has a home. A crontab change, recorded here when made. Revised by the contract release, step 1: the tick's flow pass is off and the drain line STAYS. Traced there duty by duty, the registration queue (every replay's spine half, its post-steps and the queue's own reaper, retries and pages), the trigger's producer half and the deferral scan have no other home; only the drain's derivation half went. Removing the line would stop every registration, so it waits until the registration queue has one.
  • The explanation corpus's missing slots (#956 round-2 SF-3 and N4): a routed Morpho Blue WithdrawCollateral (Bundler3's adapter as receiver), one Blue Liquidate, and an ERC-4626 Deposit log, so that dropping any of them from its filter fails a recorded case. (The same review's SF-1, the checksummed-copy cell, is fixed in S7.) Done in the contract release, step 1: all three recorded from mainnet, each killed by the mutation it guards against; SF-1's cell verified.
  • Delete the W9 / W10 residue (§9): whatever still names the two shapes this release retired. Taken by the contract release, step 2 (v0.76.0, 2026-10-04).
  • Decide WETH wrap and unwrap (#956 F1, Fred's decision; asked for before S4 shipped, and open when this entry was written). WETH9 moves a balance by Deposit and Withdrawal, never by a Transfer, and no stream ingests either, so every direct wrap or unwrap by a tracked wallet books an unexplained WETH correction (step 9.2): a page, a "cause under review" line and a stretch that is not measured. Either ingest and decode the two events (a stream, a decoder, and a re-derivation of the wallets that wrapped, which replaces each correction with the movement), or accept a cause for them in accepted-causes.ts (no page, and the line joins the accepted corrections' summary line, R5c). Decided 2026-09-27 (issue #966): ingest and decode, with native ether's own receipts, in the native-ether receipts release; this item leaves the contract release's list when that entry has run.

Everything else the sub-PRs carried, which is neither a step of this release nor the contract release's (writer checks before an outside cohort, the fixture and the harness, the adapter contract's routing, docs, staging), is listed in plan §11.

Sign-in serves the history build as it stands; the drain retries parks hourly (PR #974): what the first ticks do ​

  • belongs to: PR #974 (fix/signin-no-requeue-empty: sign-in and add-wallet re-queue only a verdict nothing has read for 12h, the drain's hourly retry of a parked build, the 6h tick's empty read stamp), no migration — the release carrying it
  • executed: 2026-09-28

Run 2026-09-28 (v0.73.0, release PR #980, merge 24973735, deployed 20:29:26Z): nothing to run, and nothing moved. The two counts were taken BEFORE the merge (20:23Z) and again after the deploy (20:42Z and 20:47Z), with the same answers: the parks query returns no row (prod holds no error row at all), empty_unstamped is 0, and the third count PR #974's review asked for, the parks at the ceiling (status = 'error' AND (attempts >= 8 OR error LIKE 'backfill child timed out%' OR error LIKE 'orphaned mid-run%')), is 0. portfolio_backfill_state held 8 done and 1 empty. Drain pages: none through 20:47Z; the minutely drain ran 19 ticks after the deploy with nothing to retry, and with no park on record its retry path has nothing to page about. No wallet to re-queue by hand. Wave 2's one candidate is the empty wallet 0x46a2…b3f2 (verdict 11:29Z): it reads as unread from 23:29Z until the first 6h tick after the deploy (00:50Z) stamps it, so a sign-in in that window rebuilds it once, as item 2 says.

What it changes for a user, in one line: a return visit no longer rebuilds a wallet whose build found nothing or failed; a failed build is retried by the queue on its own clock, and a wallet is rebuilt at a visit only when nothing read it while nobody tracked it.

No migration, no data step, nothing to run. Two waves follow the deploy on their own, and both are read-only to check. Take the counts BEFORE the release reaches prod, so the pages that follow are expected rather than investigated:

bash
sudo -u postgres psql -d creddit -c "
  SELECT attempts, count(*) AS parks,
         count(*) FILTER (WHERE updated_at < now() - interval '1 hour') AS rested
    FROM onchain_credit.portfolio_backfill_state
   WHERE status = 'error' AND attempts < 8
     AND coalesce(error, '') NOT LIKE 'backfill child timed out%'
     AND coalesce(error, '') NOT LIKE 'orphaned mid-run%'
   GROUP BY attempts ORDER BY attempts"
sudo -u postgres psql -d creddit -c "
  SELECT count(*) AS empty_unstamped FROM onchain_credit.portfolio_backfill_state
   WHERE status = 'empty' AND updated_at <= now() - interval '12 hours'"
  1. The parks already on record are retried, and every failing retry pages. On the drain's first minutely tick after the deploy, every parked build the first query lists as rested is re-queued once (a timed-out or orphaned run never is; a writer-contention park stays the self-heal's, on its fifteen minutes, as before), and after that once an hour while it keeps failing. Budget the pages at up to 8 − attempts per wallet: four for a park the drain wrote (it parks at attempts = 4), and up to eight for an older one below that (a park the CLI wrote, or one from before the minutely budget was raised to 4), because the retry sends it through the minutely budget first. A wallet that heals stops paging at once. Each page says which retry it was and whether another is coming (automatic retry k/4 in ~60min); the last one of a wallet that never heals reads retry budget SPENT, no automatic retry is left, re-queue by hand, and that wallet is yours (the repair runbook).
  2. An empty wallet may rebuild once in the first six hours. The empty read stamp is new, so until the first 6h tick after the deploy stamps them, every empty row the second query counts reads as unread. A sign-in to one of those wallets (or an add of one) in that window re-queues it once for a fresh build: about a minute of the building state, ending empty again with a fresh stamp. That is the pre-release behaviour, once, where the old rule did it on every visit. After the first tick only a wallet that left the reading population rebuilds.
  3. Record here the date the release reached prod, the two counts, and the number of drain pages the first four hours carried, and set executed: to that date.

Validating on staging first: staging runs no 6h tick, so nothing stamps an empty row there but its own verdict, and a visit more than 12h after it rebuilds the wallet once (as a done wallet with no snapshot and no anchor movement already is there). Check the served-as-it-stands arm with a wallet whose verdict is under 12h old, and the rebuild with one whose verdict is older.

The native-ether receipts release (migration 118): prod steps, in order ​

  • belongs to: issue #966 (native ether's transfers, fees and WETH9 wraps as ledger receipts; the native-eth block feed; the audit's transfer listing), migration 118
  • executed: 2026-09-28

Run 2026-09-28 by hand (v0.72.0, release PR #968, merge 6cfbd4cb, deploy run 36394170911). Step 1: 118 applied BEFORE the deploy from the staging checkout (ledger 07:53:34Z). Step 2: no environment change (no INGEST_NATIVE_* key in .env.local). Step 3: the feed's first cycle read 1 call and 20 CU over 9 tracked wallets. Step 4: the native-eth marker stamped after the cursor existed (07:55:27Z). Step 5: the 9 per-wallet wallet-token certificates reset with the ingester stopped and re-earned by the catch-ups (0 enrolled without a live row). Step 6: native-history: APPLIED; wallets 9; blocks 246041 in 493 window(s); rows 254; provider calls 246273 (4925460 CU, 4926420 throughput CU, paced at 3000 throughput CU/s). Step 7: the 8 wallets with ledger rows re-derived (rederive jobs 08:27 to 08:30Z, all done); the accepted native-ether corrections fell from 37 to 4, and the two pre-history residues left (0xef08…'s ETH at 25,986,307 and 0xe51d…'s PYUSD at 26,072,222) were hand-marked accepted with cause pre-history-balance (hand-accepted 2026-09-28 pending the opening fix, #966 follow-up). No key rotation (Fred decided against it). By v0.73.0's release (20:23Z) the accepted native-eth-transfer count read 5, and the re-audits of the window-start openings removed all five, each after its break's sources answered in full.

What it changes for a user, in one line: native ether stops producing a balance adjustment at almost every reading. Its transfers, its network fees and its wraps and unwraps become proper lines, and ether a contract pays a wallet is found at the next reading and recorded as a transfer. The existing accepted adjustments are replaced by those lines when step 7 re-derives each wallet. Expand only: nothing is wiped, and a code rollback leaves native-eth rows that no previous-release read names (every raw_events read names its streams, and the previous release's derivation list does not name this one).

Staging first. The acceptance issue #966 asks for (the feed's provider calls measured with the 12 comparator wallets, and their accepted native-ether corrections falling to zero after a re-derive) is taken on staging BEFORE this release, by the attended order below; steps 3 and 7 here repeat its two checks on prod. Take this release only once that order's step 5 reads clean, or once Fred has decided to go without it (its preconditions name the case: staging's archive endpoint not answering the listing).

  1. Migration 118, BY HAND, BEFORE the deploy. It adds 'native-eth' to the two stream CHECKs (raw_events_stream_chk as NOT VALID, catalogue only, the 082 pattern; event_coverage's inline and validated). The new ingester's first cycle writes rows and coverage under the new name; without 118 both writes are refused (the feed step fails soft every cycle and holds its cursor, so nothing is lost, but nothing is read either). As for 114 to 117, the file comes from the staging checkout, whose deploy has applied it to creddit_staging:

    bash
    git -C /opt/onchain-credit-staging rev-parse HEAD                      # = the release PR's head commit
    git -C /opt/onchain-credit-staging status --porcelain -- scripts/sql   # prints nothing
    f=118-native-eth-stream
    sudo -u postgres env "PGOPTIONS=-clock_timeout=10s -cstatement_timeout=300s" \
      psql -v ON_ERROR_STOP=1 -X -q -1 -d creddit -f /opt/onchain-credit-staging/scripts/sql/$f.sql \
    && sudo -u postgres psql -q -d creddit -c "INSERT INTO onchain_credit.schema_migrations(filename) \
         VALUES ('$f.sql') ON CONFLICT DO NOTHING"

    Idempotent; one that aborts on lock_timeout is run again when quiet. Check: SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conname IN ('raw_events_stream_chk', 'event_coverage_stream_chk') names native-eth in both (the file's own acceptance block raises otherwise).

  2. The environment: nothing to add, on a pay-as-you-go plan or above. Production's ETHEREUM_RPC_URL and ETHEREUM_ARCHIVE_RPC_URL are Alchemy's, which serves eth_getBlockReceipts (the feed) and alchemy_getAssetTransfers (the audit's listing). The feed's knobs default correctly and stay unset (INGEST_NATIVE_FEED, INGEST_NATIVE_MAX_BLOCKS, INGEST_NATIVE_CONCURRENCY, and INGEST_NATIVE_CU_PER_SEC, the feed's throughput budget: 2,000 Alchemy throughput CU a second, a fifth of pay-as-you-go's 10,000 cap; the table). Read the plan on Alchemy's dashboard first: on a plan whose per-second cap is below pay-as-you-go's, set INGEST_NATIVE_CU_PER_SEC in .env.local under that cap with the ingester's other calls left room (the sizing), and give step 6 a matching --cu-per-sec.

  3. The deploy (merge staging into main), which restarts the ingester and the worker. The ingester's first cycle starts the native-ether feed AT the scan tip (a stream with no cursor starts there; history is step 6's) and stamps one native-eth coverage row per enrolled wallet at that block. Read its log after two cycles:

    bash
    pm2 logs creddit-event-ingester --lines 80 --nostream | grep 'ingester/native-eth'
    # [ingester/native-eth] scanned [A,B] wrote N row(s) · C call(s), X CU, Y throughput CU · W tracked wallet(s) · coverage begun for W   (first cycle)
    # [ingester/native-eth] scanned [A,B] wrote N row(s) · C call(s), X CU, Y throughput CU · W tracked wallet(s)                          (after)

    What moves at once, and why step 7 should not wait long. The ether leg is an ordinary leg from this deploy on, booked by the law rather than 0 by construction (CN-3 is gone from every coverage report). So until step 7 re-derives a wallet, each ACCEPTED native-ether correction it already carries reads as what any correction reads as: its stretch of the ether leg is "not measured" (W11) instead of folded under CN-3. No figure is invented either way, and step 7's re-audits replace those corrections with the movements, which is what ends the stretches.

    C is at most 2 × (B − A + 1) and X at most 40 × (B − A + 1), whatever W is: at most two calls per block (one where no tracked wallet took part). A feed error line is a failed read the next cycle retries; one that repeats every cycle is an outage (a refused method prints a one-time does not serve eth_getBlockReceipts warning and falls back instead); a line naming blocks read "with their transactions' own receipts after their block receipts failed the check" is the feed getting past a block the provider answers inconsistently, not a failure. Record the first cycles' blocks, C, X, Y and W in the PR beside staging's measurement (the estimate: at most 40 CU a block, about 8.6M CU a month).

  4. Stamp the native-eth rollout marker, AFTER step 3's first cycle wrote the stream's cursor. From the marker on, the ingested tip the continuous producer and the served stamp follow waits for the feed's cursor too, so no range is derived ahead of the ether rows in it. Before the cursor exists the marker would read it as 0 and pin the tip there, which is why this is not earlier:

    bash
    sudo -u postgres psql -d creddit -c "SELECT last_scanned_block FROM onchain_credit.chain_scan_cursors WHERE chain_id = 1 AND scope = 'ledger:native-eth'"   # one row
    sudo -u postgres psql -d creddit -c "
      INSERT INTO onchain_credit.event_coverage (chain_id, stream, address, from_block, to_block, status, updated_at)
      VALUES (1, 'native-eth', '*', 22527558, 22527558, 'live', now())
      ON CONFLICT (chain_id, stream, address) DO UPDATE SET status = 'live', from_block = LEAST(onchain_credit.event_coverage.from_block, 22527558), updated_at = now()"

    The marker is the on-switch only (claim (a), the rollout marker): native-eth is in no venue's required scopes, so it certifies nothing and withholds no wallet.

  5. Reset wallet-token's per-wallet certificates (WETH9's Deposit and Withdrawal joined its topics, so every row below the change was earned without them). Stop the ingester for the delete, so no in-flight catch-up re-stamps a row underneath it, then start it: each enrolled wallet's catch-up re-earns its row over its window with the widened topics, three wallets a cycle.

    bash
    pm2 stop creddit-event-ingester
    sudo -u postgres psql -d creddit -c \
      "DELETE FROM onchain_credit.event_coverage WHERE chain_id = 1 AND stream = 'wallet-token' AND address <> '*';"
    pm2 start creddit-event-ingester && pm2 save
    # wait for the catch-ups: no wallet left without a live row
    sudo -u postgres psql -d creddit -c "
      SELECT count(*) AS enrolled_without_row FROM onchain_credit.account_wallets w
       WHERE NOT EXISTS (SELECT 1 FROM onchain_credit.event_coverage c
                          WHERE c.chain_id = 1 AND c.stream = 'wallet-token' AND c.address = lower(w.wallet) AND c.status = 'live')"

    While a wallet's row is missing, its derivation defers (the enrolment gate), exactly as at a signup; the query reaching 0 ends it. Take step 7 only after it does.

  6. The native-ether history run, once, after step 3 (the run refuses while an enrolled wallet has no coverage start) and before step 7: the same two reads per block over the enrolled wallets' window, for all of them at once, lowering each wallet's coverage start over what it read (how). Its --from is the oldest reading any enrolled wallet has:

    bash
    cd /opt/onchain-credit
    set -a; . ./.env.local; set +a
    FROM=$(sudo -u postgres psql -At -d creddit -c "SELECT min(block_number) FROM onchain_credit.portfolio_position_snapshots WHERE chain_id = 1")
    # 1. dry run: the blocks and the most calls and CU (two and 40 per block); reads and writes nothing
    npx tsx scripts/ops/backfill-native-eth.ts --db-url "$DATABASE_URL" --from "$FROM"
    # 2. apply: resumable and idempotent, one line per 500-block window (its calls, CU, throughput CU)
    npx tsx scripts/ops/backfill-native-eth.ts --db-url "$DATABASE_URL" --from "$FROM" --concurrency 16 --apply | tee /tmp/native-history.log

    About 216,000 blocks for a 30-day window (at most 432,000 calls and 8.6M CU, once). It spends at most --cu-per-sec throughput CU a second (3,000 by default, beside the live feed's 2,000, under pay-as-you-go's 10,000), so the width only keeps enough blocks in flight to use that budget: with today's population most blocks need no receipt (20 throughput CU each) and the run is bound by the endpoint's latency, which --concurrency 16 spreads. Check: its last line reads APPLIED, and SELECT count(*) FROM onchain_credit.event_coverage WHERE chain_id = 1 AND stream = 'native-eth' AND address <> '*' AND from_block > $FROM is 0.

  7. GATED: re-derive every enrolled wallet over its window, so the ether rows steps 3 to 6 wrote become ledger rows, and the re-audits the re-derivations queue replace the existing accepted native-ether adjustments with them (each reading's audit restates its rows to the residue that is left). A prod write: take it with explicit approval, after step 5's query reached 0 and step 6 applied.

    bash
    sudo -u postgres psql -d creddit -v ON_ERROR_STOP=1 -c "
      INSERT INTO onchain_credit.portfolio_derive_jobs (chain_id, wallet, from_block, to_block, priority, kind)
      SELECT 1, a.uid,
             CASE WHEN a.history_floor_ts IS NULL OR a.history_floor_block IS NULL THEN 24136053
                  ELSE GREATEST(a.history_floor_block, 24136053) END,
             (SELECT max(last_scanned_block) FROM onchain_credit.chain_scan_cursors
               WHERE chain_id = 1 AND scope LIKE 'ledger:%'),
             30, 'rederive'
        FROM onchain_credit.accounts a
       WHERE EXISTS (SELECT 1 FROM onchain_credit.portfolio_flow_events_v2 f
                      WHERE f.chain_id = 1 AND f.wallet = a.uid)"

    The population is every wallet the ledger holds rows for, each over its own window (its account row's recorded floor, the hand-insert rules); to_block is the newest block any stream has scanned, where the writer stops either way.

    The worker runs them (and the audits they queue). Done when SELECT kind, state, count(*) FROM onchain_credit.portfolio_derive_jobs WHERE chain_id = 1 AND kind IN ('rederive', 'audit') GROUP BY 1, 2 shows no queued or running row. Then the acceptance, read before and after:

    sql
    -- the accepted native-ether corrections: expected to fall to (near) zero
    SELECT count(*) FROM onchain_credit.portfolio_flow_events_v2
     WHERE kind = 'adjustment' AND explain_status = 'accepted' AND cause = 'native-eth-transfer';
    -- the ether receipts: transfers, fees and wraps now on the ledger
    SELECT kind, count(*) FROM onchain_credit.portfolio_flow_events_v2
     WHERE position_key = 'wallet:token:0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' GROUP BY 1 ORDER BY 1;

    What pages now: a native-ether residue left after the feed and the listing both answered for its range is unexplained (a missed movement or a source defect, never routine), and the audit's page names it. An accepted one is left only where a source could not speak (a listing outage, a block the feed did not read).

Staging, before the release: the acceptance issue #966 asks for ​

Two checks, on the 12 comparator wallets (plan §7.1, tests/comparator/old/manifest.json): the feed's provider calls per cycle, measured, and those wallets' accepted native-ether corrections (45 on 2026-09-26, plan §10) falling to zero after a re-derive. Staging runs no ingester and no worker (the hand-run rule), so every step is an attended hand-run from the staging checkout, one at a time, with PG_POOL_MAX=4, over the population alone, exactly as the ledger-first staging order ran; no command here names pm2 or touches creddit. Each step's command, start and end and summary lines go into the PR's comment.

0. The shell, and the preconditions, read rather than assumed. This PR merged into staging and deployed (the staging deploy's migrate.sh applies 118, an expand-only file); the population still enrolled (the 03:00 reseed truncates the accounts graph: /root/.reseed-paused present, or the population re-enrolled first as plan §7.2 did); and staging's endpoints answering the two methods, the live one eth_getBlockReceipts (the feed) and the archive one alchemy_getAssetTransfers (the audits' listing). The two probes print the start of each answer, never the URL, which carries the key:

bash
cd /opt/onchain-credit-staging
set -a; . ./.env.local; set +a
printf '%s\n' "$DATABASE_URL" | grep -c '/creddit_staging'   # 1: this shell writes staging's database
grep -c PG_POOL_MAX .env.local                              # 0: a value there would win over the command line's
sudo -u postgres psql -At -d creddit_staging -c "SELECT count(*) FROM onchain_credit.schema_migrations WHERE filename = '118-native-eth-stream.sql'"   # 1
W=$(node -p 'require("./tests/comparator/old/manifest.json").wallets.join(",")')
sudo -u postgres psql -At -d creddit_staging -c "SELECT count(*) FROM onchain_credit.accounts WHERE uid = ANY ('{$W}'::text[])"   # 12
umask 077
curl -s "${ETHEREUM_RPC_URL:-https://ethereum-rpc.publicnode.com}" -H 'content-type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"eth_getBlockReceipts","params":["latest"]}' | head -c 100; echo   # a "result":[{ …
curl -s "${ETHEREUM_ARCHIVE_RPC_URL:-https://eth.drpc.org}" -H 'content-type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"alchemy_getAssetTransfers","params":[{"fromBlock":"0x0","toBlock":"0x1","category":["external"],"maxCount":"0x1"}]}' | head -c 100; echo   # a "result":{"transfers" …

If the second probe answers method not found (staging's archive endpoint is not Alchemy's), every audit's listing is an unavailable source and the corrections cannot fall to zero here: stop after step 2 (the measurement stands on its own), and the choice between an Alchemy archive endpoint for staging and taking the second check on prod alone (step 7 above) is Fred's. Staging's key may be production's own Alchemy app: the throughput budgets below are what leave production its headroom.

1. Before. The population's corrections as they stand:

bash
sudo -u postgres psql -d creddit_staging -c "
  SELECT explain_status, cause, count(*) FROM onchain_credit.portfolio_flow_events_v2
   WHERE chain_id = 1 AND kind = 'adjustment' AND wallet = ANY ('{$W}'::text[])
   GROUP BY 1, 2 ORDER BY 1, 2"

2. The feed, measured: an attended ingester hand-run. Its first cycle starts the feed at the scan tip (a stream with no cursor starts there) and stamps one native-eth coverage row per enrolled wallet; every cycle prints the step's line.

bash
date -u
for i in 1 2 3 4 5; do PG_POOL_MAX=4 INGEST_SINGLE_CYCLE=1 scripts/ingester/run-ingester.sh; sleep 60; done \
  2>&1 | tee /tmp/staging-native-ingester-$(date -u +%FT%H%M%SZ).log
date -u
grep -h 'ingester/native-eth' /tmp/staging-native-ingester-*.log
# [ingester/native-eth] scanned [A,B] wrote N row(s) · C call(s), X CU, Y throughput CU · W tracked wallet(s) …

The measurement: for each cycle, the blocks B − A + 1, C, X, Y and W. It holds when C ≤ 2 × (B − A + 1) and X ≤ 40 × (B − A + 1) at the W staging tracks, and the calls do not depend on W by construction: they are one body per block and the receipts the tracked wallets need, which the SCALE cells in native-feed.test.ts and native-eth.test.ts hold equal at 5 wallets and at 50,000. Tear down as the hand-run rule says (no process left with the staging cwd).

3. The history run over the population's window, the tool of prod step 6, restricted to the population, from its oldest reading:

bash
FROM=$(sudo -u postgres psql -At -d creddit_staging -c "SELECT min(block_number) FROM onchain_credit.portfolio_position_snapshots WHERE chain_id = 1 AND wallet = ANY ('{$W}'::text[])")
date -u
PG_POOL_MAX=4 npx tsx scripts/ops/backfill-native-eth.ts --db-url "$DATABASE_URL" --from "$FROM" --wallets "$W" | tee /tmp/staging-native-history-dry.log
PG_POOL_MAX=4 npx tsx scripts/ops/backfill-native-eth.ts --db-url "$DATABASE_URL" --from "$FROM" --wallets "$W" --concurrency 16 --apply | tee /tmp/staging-native-history-apply.log
date -u
sudo -u postgres psql -At -d creddit_staging -c "SELECT count(*) FROM onchain_credit.event_coverage WHERE chain_id = 1 AND stream = 'native-eth' AND address = ANY ('{$W}'::text[]) AND from_block > $FROM"   # 0

Check: the apply's last line reads APPLIED with its calls, CU and throughput CU (record them), and no population wallet's coverage starts above $FROM.

4. Re-derive the population, then drain the queue: the INSERT of the ledger-first staging order's step 4 (psql prints INSERT 0 12), then bounded worker hand-runs, a minute apart, until the queue shows no queued and no running row. The worker's audits are what ask the listing, on staging's archive endpoint.

bash
sudo -u postgres psql -d creddit_staging -c "SELECT kind, state, count(*) FROM onchain_credit.portfolio_derive_jobs WHERE chain_id = 1 AND wallet = ANY ('{$W}'::text[]) GROUP BY 1, 2 ORDER BY 1, 2"
PG_POOL_MAX=4 LEDGER_WORKER_EXIT_WHEN_IDLE=1 bash scripts/worker/run-worker.sh 2>&1 | tee -a /tmp/staging-native-worker.log

Check: every rederive ends done, and grep -c -- '-> failed' /tmp/staging-native-worker.log prints 0.

The listing's meter (PR #967 review round 3, SF-4): how often a reading breaks on the ether leg, which is what the transfer listing's cost follows (about 240 CU a break). Step 4's audits compared the population's readings over the window the feed now covers, and the worker printed one native-ether break line for each break it asked the listing about (one line per explanation, so a break a re-audit explains again counts again, as its listings do):

bash
sudo -u postgres psql -At -d creddit_staging -c "SELECT count(DISTINCT (wallet, block_number)) FROM onchain_credit.portfolio_position_snapshots WHERE chain_id = 1 AND wallet = ANY ('{$W}'::text[]) AND block_number >= $FROM"   # R: readings compared
grep -c 'native-ether break @' /tmp/staging-native-worker.log                                  # B: breaks, two listings each
grep 'native-ether break @' /tmp/staging-native-worker.log | grep -c 'sources complete'       # of which every source answered

Record R, B and B / R, the share of readings that break: the input to the listing's 50,000-wallet figure (50,000 × 4 readings a day × B / R × 240 CU a day). Twelve wallets make it an indication, not a statistic; say so beside the number.

5. The acceptance. Step 1's query again, and the ether receipts the ledger now holds:

bash
sudo -u postgres psql -d creddit_staging -c "
  SELECT explain_status, cause, count(*) FROM onchain_credit.portfolio_flow_events_v2
   WHERE chain_id = 1 AND kind = 'adjustment' AND wallet = ANY ('{$W}'::text[])
   GROUP BY 1, 2 ORDER BY 1, 2"
sudo -u postgres psql -d creddit_staging -c "
  SELECT kind, count(*) FROM onchain_credit.portfolio_flow_events_v2
   WHERE chain_id = 1 AND wallet = ANY ('{$W}'::text[])
     AND position_key = 'wallet:token:0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'
   GROUP BY 1 ORDER BY 1"
sudo -u postgres psql -d creddit_staging -c "
  SELECT wallet, reading_block, qty_delta FROM onchain_credit.portfolio_flow_events_v2
   WHERE chain_id = 1 AND kind = 'adjustment' AND wallet = ANY ('{$W}'::text[])
     AND (cause = 'native-eth-transfer' OR (explain_status = 'unexplained' AND position_key LIKE 'wallet:token:0xeeee%'))
   ORDER BY 1, 2"

It holds when the accepted native-eth-transfer corrections are 0 and no unexplained one sits on the ether leg; the ether leg's receipts are transfer_in, transfer_out, cost and the wraps' internal_in / internal_out. A correction the last query still lists is either an accepted one, where a source could not speak for its reading's range (a listing that failed, a block the history run did not reach), which is a finding for the PR with the reading named, or an unexplained one, which is a missed movement and blocks the release until it is explained.

The wsrUSD profile (migration 119): prod steps, in order ​

  • belongs to: the wsrUSD asset profile (PR #972, branch feat/wsrusd-profile), migration 119
  • executed: 2026-09-28

Run 2026-09-28 (v0.73.0, release PR #980, merge 24973735, deploy run 36479434009, deployed 20:29:26Z). Step 1: 119 applied by hand at 20:28:05Z, BEFORE the merge, from the staging checkout at the release PR's head 70cad645 (scripts/sql clean); the ledger row read back, both rows read exactly the expected text, and the CHECK names reservoir_savings. Step 2: the deploy restarted the app, the ingester and the worker on v0.73.0. Step 3: refresh-assets by hand 20:30:46 to 20:33:55Z, done in 188294ms — 14 ok, 0 failed, 0 partial: the profile row written at 20:32:56Z (APY 5.68%, issuer Reservoir; [yield-token-assets] 17 ok, 16 before); rUSD's catch-up one chunk over 2026-09-17 10:00 to 20:30Z, newest bar 18:00Z and 273 hourly bars since the retirement, no hole; the capacity pass 9 route(s) read, 0 failed (8 before), wsrUSD through reservoir_savings: mint 192,166,261.62 rUSD of room (cap 300M, total assets 107,833,738.38), redeem uncapped (minter role held), no refusal; its loopable flag went unknown to true. Step 4: the scope query listed ONE wallet, 0xe51d05913b0951cf8b48596274bd086efdcc3ed9, through the Morpho branch alone (two wsrUSD-collateral markets, a liquidation at 25,966,539 inside its window, no wsrUSD or rUSD Transfer); rederive job #166 over [25828484, 26078314] ended done in 18.8s (1 written, 167 unchanged, 0 removed). The worker's first-movement rule then opened 3 legs from the chain (PYUSD at 25,867,076, crvUSD at 25,918,986, RLUSD at 25,962,194), and the audit it queued removed 0xe51d…'s hand-accepted PYUSD correction at 26,072,222 (1 removed), ahead of the opening step. Both audits (#167, #168) ended partial on 12 unread readings (legs the chain held and no reading read: its PYUSD from 25,871,536, its CRV at 25,921,754); the hourly arm judges the newest two readings and read ok. Step 5: no backfill; the optional erc4626 re-scan over the retirement gap was not run (harmless, as the step says).

What it changes for a user, in one line: wsrUSD gets an asset profile, and a wallet holding wsrUSD (bare, or posted as Morpho collateral) is valued, charted in the USD view and linked to that profile, valued at Reservoir's redemption rate times rUSD's market price. Expand only: two registry rows re-activated and one CHECK widened; nothing is deleted.

Decided (Fred, 2026-09-28; PR #972 review, S1): rUSD's live tip follows the standard rule, the live vendor level (CoinGecko, then DefiLlama) inside the 3% band, like every other market-priced asset. rUSD trades about $1k a day, so expect its tip to wobble more than most (it read $1.007 against a stored hourly series of $0.9992 to $1.0002), and every wsrUSD holding's headline value moves with it. Nothing to do for it in the steps below.

  1. Migration 119, BY HAND, BEFORE the deploy, from the staging checkout (the 118 / 111 pattern). migrate.sh cannot do this step before the deploy: it reads the SQL files of the checkout it runs in, and /opt/onchain-credit tracks main, which has no 119 until the deploy lands, so it would report 0 applied and exit 0 for having done nothing. Applying it first is safe for the previous release (its loader bounds capacity_reader against a vocabulary without the new kind and reads it back as NULL) and means the deploy's own restarts load the new registry rows.

    bash
    git -C /opt/onchain-credit-staging rev-parse HEAD                      # = the release PR's head commit
    git -C /opt/onchain-credit-staging status --porcelain -- scripts/sql   # prints nothing
    f=119-wsrusd-profile
    sudo -u postgres env "PGOPTIONS=-clock_timeout=10s -cstatement_timeout=300s" \
      psql -v ON_ERROR_STOP=1 -X -q -1 -d creddit -f /opt/onchain-credit-staging/scripts/sql/$f.sql \
    && sudo -u postgres psql -q -d creddit -c "INSERT INTO onchain_credit.schema_migrations(filename) \
         VALUES ('$f.sql') ON CONFLICT DO NOTHING"
    sudo -u postgres psql -d creddit -At -c "SELECT symbol, status, wallet_tracked, book, class, valuation, feed, underlying_address, rate_kind, rate_getter, liquidity, mint_terms, redeem_terms, capacity_reader, profile_ticker, issuer FROM onchain_credit.portfolio_tokens WHERE chain_id = 1 AND address IN ('0xd3fd63209fa2d55b07a0f6db36c2f43900be3094', '0x09d4214c03d01f49544c0448dbe3a27f768f2b34') ORDER BY 1"

    Expect, whatever else prod's rows drifted to before the retirement (119 sets only the columns it names, so a drifted one shows here rather than being reset silently):

    text
    rUSD|active|t|USD|par|market|dune_tape||||secondary|||||Reservoir
    wsrUSD|active|t|USD|variable_rate|composed||0x09d4214c03d01f49544c0448dbe3a27f768f2b34|getter|{"kind": "erc4626", "divisorPow10": 18}|primary_buffer|capped|instant|reservoir_savings|wsrUSD|Reservoir

    If this step is taken AFTER the deploy instead, migrate.sh from /opt/onchain-credit applies it, and the app, the ingester and the ledger worker must then be restarted: each reads the registry once, at start (the restart rule).

  2. The deploy (merge staging into main).

  3. The first six-hourly refresh-assets tick does the rest, and can be run by hand once the deploy has finished (never during it: the build prerenders from the database): scripts/run-cron.sh refresh-assets.ts. Then check, rather than reading counts off the log:

    • the profile row is written: SELECT ticker, name, issuer, current_apy, updated_at FROM onchain_credit.assets WHERE ticker = 'wsrUSD' returns one fresh row (a failure prints [yield-token-assets/fail] wsrUSD in the log). /asset-profiles is ISR (revalidate = 3600), so the page shows it within the hour;
    • rUSD's price series caught up: the mirror sync plans rUSD as a catch-up from its stored cursor (2026-09-17 10:00, when 105 retired it), so the retired stretch is loaded in one chunked Dune execution rather than skipped. SELECT max(bar_ts) FROM onchain_credit.token_price_bars WHERE token_address = '0x09d4214c03d01f49544c0448dbe3a27f768f2b34' is within the last few hours;
    • the capacity pass read wsrUSD through the reservoir_savings reader: a mint leg (the notional cap's headroom, about 192M rUSD on 2026-09-28) and an uncapped redeem leg. A route-revoked refusal means wsrUSD has lost rUSD's minter role and every redemption would revert, which is a finding for Fred, not a flake.
  4. Re-derive the enrolled wallets that ever touched wsrUSD or rUSD, and only those: a prod write, taken with explicit approval. Their transfers are already ingested (the wallet-token stream reads every ERC-20 Transfer touching an enrolled wallet, retired token or not), but every ledger row for them was derived while the two rows were retired, so it carries that answer until the wallet is derived again. Scope it read-only first; each branch is its own EXISTS, so each uses its own index (raw_events_address_block_idx, the topic indexes) rather than one filter over the whole table:

    sql
    -- read-only: the wallet list for the insert below
    WITH w AS (SELECT uid, '0x000000000000000000000000' || substr(uid, 3) AS t FROM onchain_credit.accounts),
         m AS (SELECT market_id FROM onchain_credit.morpho_market_registry
                WHERE chain_id = 1 AND collateral_address = '0xd3fd63209fa2d55b07a0f6db36c2f43900be3094')
    SELECT w.uid
      FROM w
     WHERE EXISTS (SELECT 1 FROM onchain_credit.raw_events e
                    WHERE e.chain_id = 1
                      AND e.address IN ('0xd3fd63209fa2d55b07a0f6db36c2f43900be3094', '0x09d4214c03d01f49544c0448dbe3a27f768f2b34')
                      AND e.topic0 = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
                      AND (e.topic1 = w.t OR e.topic2 = w.t))
        OR EXISTS (SELECT 1 FROM onchain_credit.raw_events e
                    WHERE e.chain_id = 1 AND e.stream = 'morpho'
                      AND e.topic1 IN (SELECT market_id FROM m)
                      AND (e.topic2 = w.t OR e.topic3 = w.t))
     ORDER BY 1;

    The Morpho branch reads both indexed parties because Morpho puts the account in either place depending on the event (the caller on SupplyCollateral and Repay, onBehalf on WithdrawCollateral and Borrow, the borrower in topic3 on a bundled supply or a liquidation). Zero rows means nothing to do. Otherwise queue one rederive per wallet with the insert the native-ether release uses (its step 7), restricted to that list (AND a.uid = ANY ('{<the list>}'::text[])), and read it done from portfolio_derive_jobs.

  5. No backfill: wsrUSD's rate series is continuous from 2025-04-29 (the yields refresher never stopped reading it), and rUSD's price series is step 3's catch-up. One known hole, harmless today: while wsrUSD was retired, the erc4626 ledger stream (whose address set follows the ACTIVE wallet-tracked rows) did not scan its Deposit / Withdraw logs, and its per-address coverage row still reads live over that stretch. Nothing derives a bare wallet leg from those events (the wallet venue reads wallet-token), so no figure moves. To close it anyway, re-scan the stream over the gap: from the block at SELECT applied_at FROM onchain_credit.schema_migrations WHERE filename = '105-coverage-rule.sql' to the block of the post-119 restart, with npx tsx scripts/backfill-event-ledger.ts --stream erc4626 --from <that block> --to <this block> (the runner); its writes are idempotent.

Paxos Gold (migration 120): first deploy ​

  • belongs to: migration 120 (PAXG joins the registry beside XAUt)
  • executed: 2026-09-28

Run 2026-09-28 (v0.73.0, release PR #980, merge 24973735). The release carried it although its PR merged into staging after the version bump (#977 at 20:11Z, so the release PR's head moved to 70cad645; CI and the staging deploy re-ran green on it). Step 4's re-check, BEFORE the deploy (20:24Z): 0 PAXG raw_events, 0 PAXG ledger rows, no registry row. Step 1: the deploy (20:29:26Z). Step 2: migrate.sh from /opt/onchain-credit at 20:30:21Z, after the checkout's SQL files were diffed against the ledger (120 the only one pending), applied 120 alone (1 applied, 119 total on disk), and the row reads PAXG|18||par|t|market|dune_tape|token|secondary|2026-09-28|manual|active. Step 3: the hand-run refresh-assets of the wsrUSD release's step 3 (20:30:46Z) was the tick: the auto-backfill took FOUR executions, not three (6.27, 5.64, 4.12 and 0.20 credits, 16.23 in all), and the series reads 2026-01-01 00:00 to 2026-09-28 18:00, 6,499 bars, every hour. Step 4: nothing to re-derive.

What it changes for a user, in one line: a wallet holding PAXG, bare or behind a Fluid position, sees it valued in dollars at its own hourly price and listed in the All view under Idle assets, the way XAUt already is. Expand only: one new registry row, nothing changed or deleted.

  1. The deploy (merge staging into main). The row is live from the first process start: the registry answers from the compiled seed with the database as an overlay, so the sweep and the feed set carry PAXG before the migration has run.

  2. Migration 120, AFTER the deploy, by the standing runner:

    bash
    cd /opt/onchain-credit && scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)"
    sudo -u postgres psql -d creddit -At -c "SELECT symbol, decimals, book, class, wallet_tracked, valuation, feed, unit, liquidity, liquidity_verified, source, status FROM onchain_credit.portfolio_tokens WHERE chain_id = 1 AND address = '0x45804880de22913dafe09f4980848ece6ecbaf78'"

    Expect PAXG|18||par|t|market|dune_tape|token|secondary|2026-09-28|manual|active. The row matches the compiled seed, so no restart is needed.

  3. The first six-hourly refresh-assets tick buys the price history, with no step of its own: the mirror's auto-backfill on add loads 2026-01-01 -> now for PAXG in three 90-day Dune executions (roughly a dozen credits, once, bounded by DUNE_MAX_CREDITS_PER_RUN). Check it after that tick: SELECT min(bar_ts), max(bar_ts), count(*) FROM onchain_credit.token_price_bars WHERE chain_id = 1 AND token_address = '0x45804880de22913dafe09f4980848ece6ecbaf78' reaches back to 2026-01-01 and forward to within a few hours.

  4. No wipe, no backfill, no re-derive. Checked read-only on 2026-09-28: none of prod's enrolled wallets held PAXG at block 26,076,359, the event store holds no PAXG transfer at all (the wallet-token stream reads every ERC-20 Transfer touching an enrolled wallet, registered token or not), and the ledger holds no PAXG row, so no stored figure was derived without it. If wallets have enrolled since, re-check before the deploy; zero means nothing to re-derive:

    sql
    -- read-only
    SELECT count(*) FROM onchain_credit.raw_events
     WHERE chain_id = 1 AND address = '0x45804880de22913dafe09f4980848ece6ecbaf78';

    A non-zero count names wallets to re-derive, queued the way the wsrUSD release's step 4 does it, with explicit approval.

The oracle cards release: the weekly check's crontab line ​

  • belongs to: the oracle cards release (branch feat/oracle-cards); no migration
  • executed: 2026-09-29

What it changes for a user, in one line: nothing on screen by itself; it makes a listed carry whose oracle card has broken or drifted page the team within a week, even if nobody opens the card.

The card needs no data step: no migration and no backfill. It is assembled at request time from approved copy and live on-chain reads. The one server step is a crontab line, on the prod box only (staging runs no scheduled refreshers), added after the release is live:

45 4 * * 1  /opt/onchain-credit/scripts/run-cron.sh check-oracle-cards.ts

Before adding it, run it once by hand. It is read-only, and a healthy run ends with All N oracle cards assemble complete, verified and live. and exit 0:

bash
cd /opt/onchain-credit && scripts/run-cron.sh check-oracle-cards.ts; echo "exit=$?"
tail -n 5 /tmp/onchain-credit-cron/onchain-credit-check-oracle-cards.log

A [fail] line names the carry and why (incomplete, drift or read); a read failure on one run only is usually the RPC, so re-run before acting on it. If it reports that Aave's risk steward no longer holds the risk-admin role, the fix is to verify the new steward contract's powers and update the fact in src/lib/data/oracle-card-facts.ts, not to edit the copy. A [warn] line (the Fluid pause-only guardian leaving or being replaced) does not page and leaves every card up; re-verify that fact at the next change.

Executed 2026-09-29 (v0.74.0, release PR #995, merge 4e9759d2, deploy run 36624568635). The hand-run first: check-oracle-cards.ts through run-cron.sh at 20:15Z, exit 0, All 38 oracle cards assemble complete, verified and live., no [fail] or [warn] line, run after the threshold refresher had filled the screener's rows (the one threshold reader step). Then the crontab line 45 4 * * 1 /opt/onchain-credit/scripts/run-cron.sh check-oracle-cards.ts added from a file (/root/crontab.daily-risk-20260929T201541Z, installed with the daily-risk edit in one crontab <file>; crontab -l | diff clean; the line counted once).

The one threshold reader release: the daily refresh line, and fill the screener's stored thresholds ​

  • belongs to: the #982 release (branch fix/one-threshold-reader); no migration
  • executed: 2026-09-29

What it changes for a user, in one line: every listed carry's expanded row states the market's real liquidation threshold (Fluid vault 17: 94%, not its 92% max LTV), the same number its oracle card prints.

No migration and no backfill. Two server steps, both on the prod box only (staging runs no scheduled refreshers), right after the release is live: the refresher's crontab line changes from weekly to daily, and the refresher is run once by hand.

1. The crontab line: weekly to daily (Fred, 2026-09-29). The line

30 3 * * 1  /opt/onchain-credit/scripts/run-cron.sh refresh-vault-risk.ts

becomes

30 3 * * *  /opt/onchain-credit/scripts/run-cron.sh refresh-vault-risk.ts

From this release a run also pages (WS8) when it reads nothing: every read failed is a [fail] line naming the count, more than 10% failed is a [partial] line, and both exit non-zero; a few failed reads are logged per carry and exit 0. Edit from a file and never through a pipe (a failing crontab -l in crontab -l | sed … | crontab - installs an EMPTY crontab):

bash
ts=$(date -u +%Y%m%dT%H%M%SZ)
crontab -l > /root/crontab.pre-daily-risk-$ts && test -s /root/crontab.pre-daily-risk-$ts
sed -E 's#^30 3 \* \* 1([[:space:]]+/opt/onchain-credit/scripts/run-cron\.sh refresh-vault-risk\.ts)#30 3 * * *\1#' \
  /root/crontab.pre-daily-risk-$ts > /root/crontab.daily-risk-$ts
test -s /root/crontab.daily-risk-$ts && diff /root/crontab.pre-daily-risk-$ts /root/crontab.daily-risk-$ts
# the diff must show exactly the refresh-vault-risk.ts line, "* * 1" -> "* * *", and nothing else
crontab /root/crontab.daily-risk-$ts && crontab -l | diff - /root/crontab.daily-risk-$ts && echo installed
crontab -l | grep -cE '^30 3 \* \* \*[[:space:]]+/opt/onchain-credit/scripts/run-cron\.sh refresh-vault-risk\.ts'   # 1

2. Fill the stored thresholds now. Until the refresher runs, a listed carry with no stored row under its live key (on 2026-09-29 that is every Fluid vault and every Morpho market) shows its threshold as a dash, because the page no longer prints the max LTV in its place. Run it once by hand rather than waiting for 03:30.

The cron logs are append-only, one file per job, so read only this run's part: lastrun below prints everything after the log's last run banner, the slice run-cron.sh itself quotes in its alerts.

bash
lastrun() { awk '/^--- .* ---$/{s=""} {s=s $0 ORS} END{printf "%s", s}' "$1"; }
cd /opt/onchain-credit && scripts/run-cron.sh refresh-vault-risk.ts; echo "exit=$?"
lastrun /tmp/onchain-credit-cron/onchain-credit-refresh-vault-risk.log | grep -E 'vault-risk-params\]|vault-risk/fail'

A healthy run prints exit=0 and [vault-risk-params] N ok, 0 failed, M changed, of N listed carries (38 listed carries on 2026-09-29; on staging that day 26 changed, the 21 Fluid vaults and 5 Morpho markets that had no row). A [vault-risk/fail] <key>: <reason> line names a carry whose read failed; nothing is written for it and it keeps the dash until a run succeeds. exit=1 with a [fail] vault-risk-params: all N reads failed or a [partial] line means the run read nothing or more than 10% failed (and, run through run-cron.sh, it pages). One failure on one run is usually the RPC: re-run before acting on it.

Then confirm the stored copy agrees with the chain. The check is read-only, and its run should print no line mentioning the screener. Read this run's slice only: a check that ran before the refresher (the Monday check, or the oracle cards step below run first) left its own "no stored liquidation threshold" lines earlier in the same file.

bash
lastrun() { awk '/^--- .* ---$/{s=""} {s=s $0 ORS} END{printf "%s", s}' "$1"; }
cd /opt/onchain-credit && scripts/run-cron.sh check-oracle-cards.ts; echo "exit=$?"
lastrun /tmp/onchain-credit-cron/onchain-credit-check-oracle-cards.log | grep "screener"   # expect nothing
lastrun /tmp/onchain-credit-cron/onchain-credit-check-oracle-cards.log | tail -n 1         # the run's summary

If the oracle cards release step ships in the same release, run this one first, so the check's first run finds the copy filled. /carries picks the rows up at its next regeneration (hourly). Staging runs no scheduled refreshers and its nightly reseed copies prod's table, so staging shows the dash for those carries until prod has run this step, unless the refresher is run there by hand after its deploy (harmless: the next reseed replaces it).

Executed 2026-09-29 (v0.74.0, release PR #995, merge 4e9759d2). Step 2 first: refresh-vault-risk.ts through run-cron.sh at 20:15Z, exit 0, [vault-risk-params] 38 ok, 0 failed, 26 changed, of 38 listed carries (the 26 = the Fluid vaults and Morpho markets that had no stored row, as staging showed); then check-oracle-cards.ts (the same run as the oracle cards step): no line mentioning the screener, All 38 oracle cards assemble complete, verified and live.. Step 1: the crontab edited from a file (/root/crontab.pre-daily-risk-20260929T201541Z → /root/crontab.daily-risk-20260929T201541Z), the diff showing exactly the refresh-vault-risk.ts line * * 1 → * * * (and the oracle cards line added in the same file); installed, crontab -l | diff clean, the daily line counted once.

The tape-dark row's vendor history (migration 121): first deploy ​

  • belongs to: migration 121 (the hole fill's vendor-history cursor, PR #985)
  • executed: 2026-09-29

What it changes for a user, in one line: an asset the Dune tape has never priced (USD3 today) gets a traded price for every hour back to its first CoinGecko quote (2026-08-30 for USD3), so a position in it is valued at market from then on instead of only from 2026-09-21.

Expand only: one nullable column, no row changed. The code PROBES for the column, so the order between the migration and the deploy is free: until the column exists the vendor history stands down and the job log carries one [partial] apply migration 121: … line naming the rows it would have loaded. The order below uses that: deploy, read the plan while nothing can be written, and only then apply the migration.

  1. The deploy (the release carrying PR #985). Until step 3 the history writes nothing.

  2. Read the plan, read-only, before the first tick can write (the tool opens a read-only session and asks no vendor):

    bash
    cd /opt/onchain-credit && (set -a; . ./.env.local; set +a; node_modules/.bin/tsx scripts/ops/plan-vendor-history.ts)

    It prints migration 121: NOT applied …, then the tape rows, how many printed inside the window, and one line per QUIET row. Expected on 2026-09-29's data: USD3 alone, as USD3 0x056b…5ecc: WOULD FILL 2026-01-01T00:00Z..<now − 49h> (the tape has never printed it; cursor none); DefiLlama alone may NOT fill an hour (a yield-bearing row with a base): its history starts at CoinGecko's first price, with four spans of which the first two show 2,112 open hours each and the last two fewer (the window's bars since 2026-09-21 are already stored), and next tick: 4 span(s) … 4 CoinGecko call(s) at most. Read it before going on, and stop if it differs:

    • USD3 SKIPPED, its floor load has not run: its tape has not been asked for its history, and the history will not start until it has. Find out why the floor load is stuck (the [price-bars] mirror auto-backfill lines of the last refresh-assets log name a guard or a failed chunk) before anything else.
    • USD3 SKIPPED, its tape sync is failing: the Dune legs are failing for it (or for the whole tape); the history waits by design until a sync succeeds. Nothing to do here but fix the Dune side.
    • Any OTHER row WOULD FILL: another tape row has printed nothing for 48 hours. Its history would be written from the vendors on the first tick, permanently. Check its tape first (a query regression, a Dune gap) and hold step 3 until it is understood.
  3. Migration 121, by the standing runner (staging auto-applies it on its deploy):

    bash
    cd /opt/onchain-credit && scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)"
    sudo -u postgres psql -d creddit -At -c "SELECT column_name FROM information_schema.columns WHERE table_schema = 'onchain_credit' AND table_name = 'token_price_sync_state' AND column_name = 'vendor_history_through'"

    Expect vendor_history_through. Re-running the plan now prints migration 121: applied and the same rows.

  4. The next six-hourly refresh-assets tick on prod loads the history, with no step of its own (staging runs no scheduled refreshers, and a hand-run there would be undone by the nightly reseed). For USD3 that is four metered CoinGecko calls and about twenty-two keyless DefiLlama calls, once. Check it after that tick, read-only:

    sql
    -- read-only
    SELECT source, count(*), min(bar_ts), max(bar_ts)
      FROM onchain_credit.token_price_bars
     WHERE chain_id = 1 AND token_address = '0x056b269eb1f75477a8666ae8c7fe01b64dd55ecc'
     GROUP BY source ORDER BY 3;
    SELECT floor_loaded, consecutive_failures, vendor_history_through
      FROM onchain_credit.token_price_sync_state
     WHERE chain_id = 1 AND token_address = '0x056b269eb1f75477a8666ae8c7fe01b64dd55ecc';

    Expect coingecko:hourly bars only, from 2026-08-30 14:00 on, every hour to within six hours of the tick, and no llama:chart bar (DefiLlama prices USD3 at its redemption rate, so it is the second opinion only); and vendor_history_through about 49 hours behind the tick. That is what the two vendors answered on 2026-09-29 when the same code filled a throwaway database from them. That tick's job log carries one [vendor-history] USD3: … line (written this pass: CoinGecko 2026-08-30..…, DefiLlama none), and every tick carries 1 row(s) the tape has never printed, each written by the vendor fill instead … where the old [partial] … check the saved query's token coverage: USD3 line used to be. If the tick logs stopped (CoinGecko did not answer), the next tick resumes from the same span; nothing to do.

  5. No wipe, no backfill, no re-derive is part of this step. A wallet whose stored snapshots were taken while USD3 had no history keeps them until it is re-derived, and USD3's historical token_basis grid points are not recomputed. The owner's call on 2026-09-29 was that the current test wallets are to be deleted anyway, so nothing is queued here; a wallet enrolled after the history lands is valued with it from its first build.

If the history ever holds a row on a [partial] vendor history of <row> waits at <day> line, the operator's cursor reset is in Data pipeline → A row the tape does not print.

Executed 2026-09-29 (v0.74.0, release PR #995, merge 4e9759d2, deploy run 36624568635 green at 20:12Z). Step 2, the plan read at 20:14Z before any tick could write (the next refresh-assets tick being 00:00Z): migration 121: NOT applied, tape rows: 58, of which 57 printed inside the window … and 1 are quiet, USD3 0x056b…5ecc: WOULD FILL 2026-01-01T00:00Z..2026-09-27T20:00Z (the tape has never printed it; cursor none); DefiLlama alone may NOT fill an hour …, four spans of 2112, 2112, 2102 and 0 open hours (the fourth already stored), next tick: 3 span(s) of the 8 a pass allows, 3 CoinGecko call(s) at most; no other row WOULD FILL, no SKIPPED. Step 3 at 20:15Z: scripts/ops/migrate.sh → APPLY: 121-vendor-history-cursor.sql, migrate creddit: 1 applied, 121 total on disk; the column vendor_history_through present; the plan re-run prints migration 121: applied (the cursor column exists) and the same rows. (Migration 122 of the contract release had been applied by hand before the merge, so the runner applied 121 alone.) Step 4, the 00:00Z tick on 2026-09-30: [vendor-history] USD3: the tape has never printed it, so the vendors write its history (2026-01-01..2026-09-28); written this pass: CoinGecko none, DefiLlama none; nothing asked yet; stopped (CoinGecko did not answer) and 1 row(s) the tape has never printed, each written by the vendor fill instead …: USD3 (vendor bars 2026-09-21..2026-09-29, older history not asked yet): the vendor did not answer on the first pass, so nothing was written (coingecko:hourly 197 bars 2026-09-21 14:00 to 2026-09-29 18:00 as before, vendor_history_through empty, floor_loaded t, consecutive_failures 0) and, as this entry says, the next tick resumes from the same span; nothing to do. The 06:00Z tick then loaded it: [vendor-history] USD3: … written this pass: CoinGecko 2026-08-30..2026-09-21, DefiLlama none; asked through 2026-09-28 and USD3 (vendor bars 2026-08-30..2026-09-30); the read-only checks: coingecko:hourly 731 bars from 2026-08-30 14:00 to 2026-09-30 00:00, no llama:chart bar, floor_loaded t, consecutive_failures 0, vendor_history_through 2026-09-28 06:00 (48 hours behind the tick). Step 5: nothing queued, as the owner decided.

The contract release, step 1: the worker owns derivation (migration 122): prod steps, in order ​

  • belongs to: issue #981, step 1 (WORKER_OWNS_DERIVATION true; PR #986, branch feat/981-worker-owns-derivation), migration 122
  • executed: 2026-09-29

What it changes for a user, in one line: nothing on screen when it works. The same ledger is derived by one background process instead of three places. A page load or Synchronize waits up to 20 seconds for its own refresh, and when that does not come back in time the page keeps the last derived state and says it could not refresh (derivation-pending). A large wallet's history build no longer holds up anyone else's refresh.

What it does, and what it leaves.

  • The 6h tick, the registration replay and the page load (Synchronize included) stop deriving and enqueue sweep, enrol and sync jobs; the minutely drain's re-derivation trigger enqueues rederive jobs. The ledger worker is the only derivation writer, besides the offline history builder (a hand-run tool). It runs a second lane for sync jobs, and never two jobs of one wallet at once (data-pipeline).

  • Migration 122, expand only: the producer column, which the three producers stamp and whose CHECK (pdj_producer_chk) refuses a sync, enrol or sweep row typed by hand, and the partial unique index pdj_one_running_per_wallet (database).

  • The minutely drain line stays, on prod and on staging. Every duty the drain runs, and where it went:

    DutyWhere it is after this release
    The registration queue: claim a queued registration and run its replay in a child process under a divided Dune budget (the spine half, the pre-window PT fills, the floor openings, the grid's audit enqueue)Stays in the drain. Nothing else claims the queue.
    The replay's ledger half (the whole-window derivation and the derive cursor's stamp)The worker's enrol job. The replay enqueues it after its own gate.
    The queue's upkeep: the stale-run reaper, the contention and parked-wallet retries, the per-failure pages (exit 2)Stays in the drain, with the queue it tends.
    The re-derivation trigger's derivationThe worker's rederive job.
    The trigger's producer half (candidates, certification, hold, arm, attempt cap, one open job per wallet)Stays in the drain.
    The deferral scan and the parked-replay overrun linesStays in the drain (it reports, and never pages).

    So the line's derivation half is gone and the line stays: removing it would stop every registration. Neither crontab changes. (The tick's own flow pass is off: its per-wallet step is the worker's sweep job, and the code behind the constant goes in step 2.)

  • No ledger row is written or removed by the release itself; the value columns stay (step 2).

Preconditions, read on the day (issue #981; each is a read):

  1. Two more days like the last 12 hours (the issue's bar): no [fail] from the hourly check, the 6h reconciler's identity holding with differ=0 (or explained by late bars), no unexplained adjustment, no failed job, and partial audits only of the unread-legs class:

    bash
    L=/tmp/onchain-credit-cron
    tail -n 300 $L/onchain-credit-check-ingester-freshness.log | grep -c '^\[fail\]'   # 0: about two days, six lines a run
    grep 'ledger-reconcile:' $L/onchain-credit-refresh-ledger-reconcile.log | tail -8   # differ=0, or a late bar named
    sudo -u postgres psql -d creddit -c "SELECT kind, state, count(*) FROM onchain_credit.portfolio_derive_jobs WHERE chain_id = 1 GROUP BY 1, 2 ORDER BY 1, 2"
    sudo -u postgres psql -d creddit -c "SELECT id, kind, left(error, 160) FROM onchain_credit.portfolio_derive_jobs WHERE chain_id = 1 AND state = 'partial' AND finished_at > now() - interval '2 days' ORDER BY id"
  2. No wallet the inline tick marks partial (S8c, below): from the first sweep on, a wallet whose tick-range derivation is partial holds the tick cursor for the whole population until a later sweep derives it cleanly. The inline tick advanced the cursor past such a wallet and recorded its debt in a pending marker, so the old log is the forecast:

    bash
    grep -E 'v2 dual-write:|\[partial\] ledger v2' $L/onchain-credit-refresh-portfolio.log | tail -8   # every tick: 0 failure(s), 0 partial

    A wallet partial at every tick is Fred's decision BEFORE this release (the watch list's S8c), never a surprise after it.

  3. No typed row in the queue (122 refuses to apply over one, and names it): SELECT count(*) FROM onchain_credit.portfolio_derive_jobs WHERE kind IN ('sync','enrol','sweep') AND state IN ('queued','running') prints 0.

  4. Fred's Synchronize on staging, against this release's code: the staging order, step 5.

Prod steps, in order.

  1. Migration 122, BY HAND, BEFORE the merge. The release's code names producer in every enqueue, so a deploy without it fails every page load's sync, every registration's enrol and the tick's sweep enqueue. The running release never names the column and its worker runs one job at a time, so 122 is safe under it. As for 118, the file comes from the staging checkout, whose deploy has applied it to creddit_staging:

    bash
    git -C /opt/onchain-credit-staging rev-parse HEAD                      # = the release PR's head commit
    git -C /opt/onchain-credit-staging status --porcelain -- scripts/sql   # prints nothing
    f=122-derive-job-producer
    sudo -u postgres env "PGOPTIONS=-clock_timeout=10s -cstatement_timeout=300s" \
      psql -v ON_ERROR_STOP=1 -X -q -1 -d creddit -f /opt/onchain-credit-staging/scripts/sql/$f.sql \
    && sudo -u postgres psql -q -d creddit -c "INSERT INTO onchain_credit.schema_migrations(filename) \
         VALUES ('$f.sql') ON CONFLICT DO NOTHING"
    sudo -u postgres psql -At -d creddit -c "SELECT count(*) FROM onchain_credit.schema_migrations WHERE filename = '$f.sql'"   # 1

    Idempotent; its acceptance block raises unless the column, the validated CHECK and the index exist, and one that aborts on lock_timeout is run again when quiet.

  2. Stop the worker, BEFORE the merge, just after an hourly check (:05), so that the stop and the deploy are over before the next one, and in an hour whose tick (:50 at 00, 06, 12 and 18 UTC) and reconciler (:30 at 01, 07, 13 and 19 UTC) fall outside that window:

    bash
    pm2 stop creddit-ledger-worker && pm2 save
    pm2 describe creddit-ledger-worker | grep -cE 'status[^a-z]+stopped'   # 1

    Why by hand, and why first. The crons run the release's code from the moment the deploy's git reset and npm ci land (they compile from source), while a running worker keeps the previous release's code until the deploy restarts it, after the build. For those minutes the new drain enqueues enrol jobs, and the previous worker REFUSES an enrol (the pre-flip rule: partial, nothing derived) while the new replay has written no deferral marker behind it, so nothing automatic would ever derive that wallet's history. Restarting the worker earlier in the deploy would narrow that window, not close it (a cron can start on the new source in the seconds before npm ci replaces the toolchain, and a failed build, which rolls the checkout back, would leave the new code's jobs to a worker restarted onto the old code), and it would change every later deploy for one release's sake. So the worker is stopped across the window and the jobs wait. Nothing is lost meanwhile: the previous app derives inline until the deploy restarts it, and the new one's page loads wait their 20 s and report derivation-pending until step 4.

  3. Merge the release PR (staging into main). The deploy restarts the app and the ingester on the new code and leaves the stopped worker stopped, with the expected ::warning::creddit-ledger-worker is stopped (a deliberate quiesce), so it was NOT restarted …; the run is green. If the build fails, the run rolls the checkout back to the previous commit: then do not start the worker as it stands; run the rollback's step 3 first (the crons ran the new code during the build), then pm2 restart creddit-ledger-worker --update-env && pm2 save.

  4. Start the worker as soon as the run is green:

    bash
    pm2 restart creddit-ledger-worker --update-env && pm2 save
    pm2 logs creddit-ledger-worker --lines 30 --nostream | grep 'starting as'   # … · with the sync lane

    It drains what waited: the enrol, rederive and sweep jobs the crons queued while it was stopped, and one sync per wallet a page load asked for since the app restarted.

  5. The crontab: no change (the drain's duties, above). Confirm both lines stand:

    bash
    crontab -l | grep -c '/opt/onchain-credit/scripts/run-cron.sh drain-portfolio-backfills.ts'           # 1
    crontab -l | grep -c '/opt/onchain-credit-staging/scripts/run-cron.sh drain-portfolio-backfills.ts'   # 1
  6. The first page load's sync: Fred presses Synchronize: refreshed: true inside the 20 s wait, and the "Updated" stamp is the derived-through block's time. The worker logs [worker] job #… sync 0x… [<from>,<to>] (derived […]) attempt 1 -> done, …, and the row reads:

    bash
    sudo -u postgres psql -d creddit -c "SELECT id, wallet, producer, claimed_by, state, round(extract(epoch FROM finished_at - created_at)::numeric, 1) AS waited_s FROM onchain_credit.portfolio_derive_jobs WHERE chain_id = 1 AND kind = 'sync' ORDER BY id DESC LIMIT 3"
    # producer page-load, state done, waited_s under 20, claimed_by ending /sync (the sync lane;
    # the main lane's id without the suffix is equally right: between two jobs it takes syncs first)
  7. The first 6h tick (50 */6) and its sweep:

    bash
    grep -E 'v2 sweep:|v2 dual-write:|liveTipsRetired' $L/onchain-credit-refresh-portfolio.log | tail -4
    pm2 logs creddit-ledger-worker --lines 600 --nostream | grep -E ' sweep |v2 tick cursor|audit'
    sudo -u postgres psql -d creddit -c "SELECT state, count(*) FROM onchain_credit.portfolio_derive_jobs WHERE chain_id = 1 AND kind = 'sweep' AND created_at > now() - interval '1 hour' GROUP BY 1"
    sudo -u postgres psql -d creddit -c "SELECT scope, last_scanned_block, updated_at FROM onchain_credit.chain_scan_cursors WHERE chain_id = 1 AND scope IN ('portfolio:v2:tick', 'portfolio:v2:tick:noted')"

    The tick's log: [portfolio] v2 sweep: N sweep job(s) enqueued over [A,B]; the worker advances the tick cursor when all are done (N = the tracked wallets); [portfolio] v2 dual-write: N wallet(s) over NO range, 0 row(s) written, … (the tick derives nothing itself now); and [portfolio] wrote … snapshot rows, 0 ledger rows, … liveTipsRetired=K …. The worker: one sweep job per wallet -> done (mostly 0 written: the continuous jobs derived the window already), then [portfolio] v2 tick cursor -> C (settle line S) once the last one is done, and the audit jobs the tick queued for its readings. The query: every sweep job done, the tick cursor at C, and the noted record at the cursor the previous tick left (the first tick only records where it starts). So this first tick, and only this one, also prints [portfolio] discovery certificates NOT advanced this tick — no scope scanned this tick …, and may print coverage conjunction vetoed N/M wallet(s) too: it has no completed sweep to note yet, so each stream falls back to its own ingester cursor. Both exit 0 and page nothing. A certificate outlives one tick without an advance (a wallet demotes only once three pass without one), and step 8's tick advances the certificates, the coverage anchors and the empty wallets' read stamps again. (An anchor last advanced by the last inline tick is 12 hours old as step 8's tick starts, so in the minutes before that tick advances it, a sign-in can rebuild an all-closed done or an empty wallet once: a replay, harmless, and only at this transition.)

  8. The second 6h tick notes the first sweep's pass: [portfolio] v2 sweep: the worker's completed sweeps derived [A,C] for the population since the last note; noted as scanned for the coverage conjunction and the certificates, and the noted record moves to C.

  9. The hourly check after the start reads ok on all four arms (ledger-derive-lag: ok: heartbeat …, 0 failed, …), and the re-derivation trigger shows its new form in the drain's log: the half-hourly [rederive] candidates=… job-open=0 … heartbeat and, for a wallet it launches, [rederive] 0x…: rederive job #N enqueued over [F,T]; … followed by the worker's rederive … -> done:

    bash
    grep '\[rederive\]' $L/onchain-credit-drain-portfolio-backfills.log | tail -3
  10. After a day, the page load's wait: the health check's number 1 (how many sync jobs took longer than the 20 s wait, and the median).

  11. Record executed: with the release PR, the merge commit, the deploy run and each step's figures.

Executed 2026-09-29 (Fred: "lets do step 1 now … when pr is ready to merge, merge it and release to prod ok?"), summary lines per step. Preconditions read at 19:33Z: the hourly check's last 300 lines held 0 [fail] (the one page since the release, 2026-09-28 12:05Z, was the pre-history-balance defect since fixed); the reconciler's identity per wallet with factless=0/0/0 everywhere (differ above zero as expected); jobs audit done 110 / partial 19 (unread legs) / continuous done 99 / rederive done 9, none failed; the last eight ticks 0 failure(s), 0 partial; no typed row in the queue (0); the staging order run on d5535265 (a scripted registration of 0xaae6… and 0xef08…, the two-lane hand-run, a page-load sync served by the sync lane in 0.2 s while a 13 s rederive ran in the main lane, a hand-run tick whose four sweep jobs, the empty wallet 0x46a2… included, all ended done and moved the tick cursor, and Fred's own sign-in and Synchronize with 0xea88…: done, the stamp at staging's frozen tip 26080001 = 02:01:35Z as expected). Step 1 at 19:33Z: 122-derive-job-producer.sql by hand from the staging checkout at 1fd0f234 (scripts/sql clean), the acceptance block silent, schema_migrations row 1, pdj_producer_chk validated, pdj_one_running_per_wallet present, the old worker unaffected. Step 2 at 20:11Z (after the 20:05Z hourly check, which ran long, finished): pm2 stop creddit-ledger-worker && pm2 save, stopped 1. Step 3: release PR #995 merged 4e9759d2 (v0.74.0, carrying #976 #978 #979 #983 #984 #985 #986); deploy run 36624568635 green at 20:12:31Z (compiled in 10 s, app restarted 20:12:27Z, ingester 20:12:30Z, the stopped worker left stopped). Step 4 at 20:12:55Z: pm2 restart creddit-ledger-worker --update-env && pm2 save, [worker] starting as ubuntu-8gb-nbg1-1:3264951 · with the sync lane, online. Step 5: both drain lines counted 1. Step 6 at 20:14Z (the operator's press through the API for 0xaae6…, Fred's own press asked for): {"refreshed":true} in 2.1 s; the row sync #253, producer page-load, claimed_by …/sync, done, waited 0.3 s; the summary's readBlock 26085380 = the ingested tip. Step 7, the first 6h tick at 00:50Z on 2026-09-30: the tick logged v2 sweep: 12 sweep job(s) enqueued over [26084928,26086750] (12 tracked wallets: the 9 of the release day plus three added that evening), v2 dual-write: 12 wallet(s) over NO range, 0 row(s) written, 0 failure(s), 0 partial in 9ms, wrote 113 snapshot rows, 0 ledger rows, 0 index rows, liveTipsRetired=60 (derived <= 26086750, ledger lag 3), and, this tick only, coverage conjunction vetoed 10/10 wallet(s) and discovery certificates NOT advanced this tick — no scope scanned this tick, exit 0, no page. The worker: twelve sweep … attempt 1 -> done between 00:50:07Z and 00:50:10Z (0xea88… and 0xb47c… 1 written, the rest 0 written; the three new wallets (derived [26078271..26078286,26086750])), then [portfolio] v2 tick cursor -> 26086745 (settle line 26086745) at 00:50:10Z; the noted record at 26084927 (the cursor the last inline tick left), the eight audit jobs the tick queued running after. Jobs of the two hours around it: sweep done 12, continuous done, no failed; adjustments on prod still 0. Step 9: the hourly check ok on all four arms at 21:05Z, 22:05Z, 23:05Z and 00:05Z (ingester-freshness … v0.74.0, ledger-derive-lag: ok: heartbeat 0h00m ago … 0 failed), and the drain's half-hourly [rederive] candidates=0 … job-open=0 … failures=0 heartbeat. Step 8, the second tick at 06:50Z: v2 sweep: 12 sweep job(s) enqueued over [26086746,26088543], then v2 sweep: the worker's completed sweeps derived [26084928,26086745] for the population since the last note; noted as scanned for the coverage conjunction and the certificates, no NOT advanced or vetoed line, liveTipsRetired=0; the worker's twelve sweeps -> done between 06:50:09Z and 06:50:11Z (all 0 written), v2 tick cursor -> 26088530 (settle line 26088530); the noted record at 26086745 (the first flipped tick's cursor) and the tick cursor at 26088530. The night's jobs: sweep done 24, continuous done 9, audit done 8 (the second tick's eight running), no failed; the hourly check ok on every arm from 01:05Z to 06:05Z; the 07:30Z reconciler paged only its three standing budget lines (the pre-existing withhold budget of three test wallets, not this release's); adjustments 0. Step 10, read on 2026-10-01 08:05Z: 25 sync jobs since the deploy, 0 over the 20 s wait, median 0.41 s, p90 0.83 s, max 1.1 s; the 3 not done are the three new wallets' first syncs of 2026-09-29 20:32Z to 20:36Z (partial: 1 scope(s) not certified to the range floor; unresolvable-universe, each wallet's next sync done). Every tick since the flip advanced the cursor (06:50Z, 12:50Z and 18:50Z on 2026-09-30, 00:50Z and 06:50Z on 2026-10-01, each noting the previous pass as scanned); 48 hours of jobs: sweep done 72, continuous done 78, audit done 96 / partial 1 (unread legs), rederive done 3, sync done 22 / partial 3 (above), no failed; the hourly check ok on every arm, no page since 2026-09-28 12:05Z; adjustments 0; the reconciler paging only its three standing budget lines. The value-parity census (read-only, scripts/ops/value-parity.ts --db-url, 11 wallets, 5,923 readings, 714 receipts, 6 fills): served stored (no rate fact) 0 on every line kind, readings late data 1718, corrected 0, residue 0, fills clean, receipts late data 2, residue 2: the two residue lines are one receipt's two books (0xe51d…, Morpho market collateral in the PT 0xd3fd…3094 at block 25966539, stored 4.62 / 4.63, computed null: the PT settles into a payout asset this product does not carry), the finding step 2 chases before the drop. The release PR's CI: every job green except e2e-interaction (narrow-900) (464 passed, 1 flaky, 1 failed: a build landing into the uncertified tail brings the WHOLE portfolio, a 20 s predicate timeout of the building-state family the review had classified as load-sensitive; the same spec passed at desktop-1360 and reduced-motion in the same run), honoured as advisory.

Rollback, and a roll-forward after it ​

Revert the release and the previous code derives inline again. No ledger row has to be deleted. The previous release's rollback deleted two ledger kinds the old code did not know (#960 review B1); this release adds no ledger kind and no column the old code reads, and the rows it derives are the same writer's rows at the same sites. What the old code does not tolerate is in the QUEUE: the producers' rows, which its worker refuses (sync, enrol) or derives as a plain range that moves nothing (sweep), and whose failures its derive-lag arm pages for.

  1. Stop the worker: pm2 stop creddit-ledger-worker && pm2 save.

  2. Revert the release commit on main (git revert -m 1 <its merge commit> on a branch off main, merged as a PR; keep the revert off staging while a roll-forward is intended, as the previous entry says). Its deploy restarts the app and the ingester on the previous code and leaves the stopped worker stopped.

  3. The queue, as soon as that deploy is green. Each registration whose ledger half is still an enrol job goes back to the previous code's own deferral path (its re-derivation trigger derives a wallet that carries the marker and no derive cursor, once the wallet's enrolment certifies), and the producers' unfinished rows go:

    bash
    sudo -u postgres psql -d creddit -v ON_ERROR_STOP=1 -1 -c "
      INSERT INTO onchain_credit.chain_scan_cursors (chain_id, scope, last_scanned_block, updated_at)
      SELECT chain_id, 'portfolio:derive:v2:' || chain_id || ':' || lower(wallet) || ':replay-deferred', max(to_block), now()
        FROM onchain_credit.portfolio_derive_jobs
       WHERE chain_id = 1 AND kind = 'enrol' AND state IN ('queued', 'running', 'failed')
       GROUP BY chain_id, wallet
      ON CONFLICT (chain_id, scope) DO NOTHING;
      DELETE FROM onchain_credit.portfolio_derive_jobs
       WHERE chain_id = 1 AND kind IN ('sync', 'enrol', 'sweep') AND state IN ('queued', 'running', 'failed');"
    sudo -u postgres psql -d creddit -c "SELECT kind, state, count(*) FROM onchain_credit.portfolio_derive_jobs WHERE chain_id = 1 GROUP BY 1, 2 ORDER BY 1, 2"
    # no queued, running or failed sync, enrol or sweep row

    A finished (done, partial) row stays: it records what was derived, and the previous code reads it the same way (the stamp's derived-through terms). A deleted sync or sweep needs no replacement: the previous page load and tick derive those ranges themselves, the tick from the cursor an unfinished sweep never moved.

  4. Start the worker on the previous code: pm2 restart creddit-ledger-worker --update-env && pm2 save. It drains continuous, audit and rederive jobs, as before this release.

  5. Nothing else. Migration 122 stays (the previous code never names producer, inserts only kinds whose CHECK arm wants it NULL, and runs one job at a time, so the index never binds); no crontab line was changed, so none is restored; the portfolio:v2:tick:noted record may stay (the previous tick never reads it, and a roll-forward's first tick notes from it the window the previous tick derived and noted itself, which is true).

A roll-forward is this release's merge again (a revert of the revert, as the previous entry's rule says), with prod steps 2 to 4 (122 is already applied).

Staging, before the release ​

Staging runs no ingester and no worker (the hand-run rule), and from this release its page loads and registrations only enqueue: nothing derives on staging while no hand-run is going. That is also staging's standing state after this release (the watch list below). So the check is an attended hand-run from the staging checkout, as the ledger-first staging order ran them: one at a time, with PG_POOL_MAX=4, and no command here names pm2 or touches creddit.

0. The shell, and the preconditions, read rather than assumed. This PR merged into staging and deployed (the staging deploy's migrate.sh applies 122). The reseed: the 03:00 reseed restores prod's schema, which lacks 122 until prod step 1, and runs no migrate.sh, so from a reseed until the next staging deploy re-applies it, every staging page load logs ledger merge failed … column "producer" … does not exist and stores nothing, and every staging registration's replay fails at its enqueue: its spine half stands, its row reads done, and it defers the wallet ([partial] … the enrol job could not be enqueued …; deferred), so the re-derivation trigger enqueues the wallet's rederive once 122 is back. Run this order after a staging deploy that followed the last reseed, or with the reseed paused (touch /root/.reseed-paused, removed after).

bash
cd /opt/onchain-credit-staging
set -a; . ./.env.local; set +a
printf '%s\n' "$DATABASE_URL" | grep -c '/creddit_staging'   # 1: this shell writes staging's database
grep -c PG_POOL_MAX .env.local                              # 0: run-worker.sh sources .env.local AFTER the
                                                            #    command line, so a value there would win
sudo -u postgres psql -At -d creddit_staging -c "SELECT count(*) FROM onchain_credit.schema_migrations WHERE filename = '122-derive-job-producer.sql'"   # 1
sudo -u postgres psql -At -d creddit_staging -c "SELECT count(*) FROM pg_constraint WHERE conname = 'pdj_producer_chk' AND convalidated"   # 1
umask 077

The hand-run takes its worker lock in creddit_staging, where nothing else holds one, so it neither waits for prod's worker nor stops it. If it prints waiting for the worker lock or a refusal naming creddit-ledger-worker, another STAGING hand-run is still going (the line names prod's process because it is written for prod): find it, never pm2 stop anything (#960 round 3, N2).

  1. Before. What staging queued since the deploy:

    bash
    sudo -u postgres psql -d creddit_staging -c "SELECT kind, state, producer, count(*) FROM onchain_credit.portfolio_derive_jobs WHERE chain_id = 1 GROUP BY 1, 2, 3 ORDER BY 1, 2, 3"

    Each page load left one queued sync per wallet (a later one widens it), and each registration an enrol once the drain replayed it; every one carries its producer's stamp.

  2. Fred signs in on staging. If the reseed emptied the accounts graph, the sign-in registers his wallet, and within a few minutes the staging drain replays its spine half and enqueues its ledger half:

    bash
    grep 'v2 ledger: enrol job' /tmp/onchain-credit-cron/onchain-credit-staging-drain-portfolio-backfills.log | tail -3
    # [backfill 0x…] v2 ledger: enrol job #N enqueued over [F,T]; the ledger worker derives it and stamps the derive cursor

    (A [v2-deferred] … v2 replay DEFERRED line instead means staging holds the wallet-token rollout marker, so the replay waits for the wallet's own bare-token catch-up, which on staging only an ingester hand-run performs. The reseed's scrub removes that marker, so after a reseed the enrol line is the one to expect.)

  3. The hand-run, with both lanes: bounded by timeout, and WITHOUT LEDGER_WORKER_EXIT_WHEN_IDLE (that mode runs one lane, and this check is the sync lane's). It opens up to twelve connections (seven for its lanes, one for the lock, four for the shared pool) of the staging role's twenty, so nothing else is hand-run beside it:

    bash
    date -u
    PG_POOL_MAX=4 timeout 1800 bash scripts/worker/run-worker.sh 2>&1 | tee /tmp/staging-contract-worker-$(date -u +%FT%H%M%SZ).log
    # [worker] starting as <host>:<pid> · with the sync lane

    timeout ends it after 30 minutes with the signal pm2 sends; Ctrl-C ends it sooner. Either way the job in flight in each lane finishes first.

  4. The queue drains. Fred's enrol (priority 10) comes first, then the others in priority order; each ends -> done in the log. His page leaves its building state once his enrolment is done.

  5. Fred presses Synchronize, with the hand-run going and his enrolment done: refreshed: true inside the 20 s wait, and the "Updated" stamp is the derived-through block's time. Then:

    bash
    sudo -u postgres psql -d creddit_staging -c "SELECT id, wallet, from_block, to_block, producer, claimed_by, state, round(extract(epoch FROM finished_at - created_at)::numeric, 1) AS waited_s FROM onchain_credit.portfolio_derive_jobs WHERE chain_id = 1 AND kind = 'sync' ORDER BY id DESC LIMIT 3"
    # producer page-load, state done, waited_s under 20; claimed_by ending /sync is the sync lane

    The second lane, if the population is enrolled: enqueue a rederive for one population wallet other than Fred's (the INSERT of the ledger-first staging order's step 4, with WHERE a.uid = '<that wallet>'; psql prints INSERT 0 1), and press Synchronize while the log shows that job running: the sync is -> done inside the 20 s, claimed by …/sync, before the rederive's own line. (Fred's own wallet would wait for its own job instead, by design: no two jobs of one wallet run at once.)

  6. Stop and read. Once the hand-run has ended:

    bash
    grep -c -- '-> failed' /tmp/staging-contract-worker-*.log   # 0
    sudo -u postgres psql -d creddit_staging -c "SELECT kind, state, count(*) FROM onchain_credit.portfolio_derive_jobs WHERE chain_id = 1 GROUP BY 1, 2 ORDER BY 1, 2"

    Anything still queued waits for the next hand-run. Record the Synchronize's wait, the jobs' verdicts and the log's name in the release PR.

  7. The drain line stays on staging too: crontab -l | grep -c '/opt/onchain-credit-staging/scripts/run-cron.sh drain-portfolio-backfills.ts' prints 1, and nothing is changed.

Watch list, and what step 2 took ​

Watch, the first days.

  • S8c, a wallet partial at every sweep holds the tick cursor for everyone (a decision for Fred, open; decided 2026-10-04: quarantine, the quarantine release). The worker logs [worker] sweep [A,B] finished with N of M job(s) not done, so the tick cursor is NOT advanced; the next sweep re-derives from it, and every sweep and continuous job then re-derives from the held cursor, so the window widens every 6h. The hold reaches past the cursor (PR #986 review, SF3): every tick after which no sweep has completed notes no scanned scope, exactly as the first flipped tick does, and that batch veto stops three things for the WHOLE population, not the one wallet: the discovery certificates (after three such ticks every wallet demotes to the slower full-universe read), the coverage anchors (after two, the 12 h sign-in guard rebuilds an all-closed done wallet on its owner's next visit), and the empty wallets' read stamps (the same for an empty one). A pageable partial (a served wallet's merge over a range it could not read) pages hourly through the derive-lag arm, and so, since this review, does ANY hold that lasts: the arm pages once no sweep has completed for 12 hours (two tick periods; LEDGER_TICK_STALL_MAX_MINUTES) while the tick has wallets to sweep, whatever the holding job's reason, a wait on a registration's own enrolment included (it clears at the next sweep only if the catch-up lands). The choice, with that cascade in view, is Fred's: quarantine a chronically partial wallet from the sweep, release the cursor once its owed range is recorded (its pending marker), or stop gating the anchors and the empty-wallet stamps on the ledger pass (the snapshot they certify is written either way; the review's option, not taken here). Precondition 2 is the forecast.
  • The page load's wait: the health check's number 1. A count over the 20 s wait that climbs means the sync lane is not keeping up, or the worker was down. What an ordinary wait is made of (PR #986 review, N5): up to about half a second of polling (the lane's claim poll and the page's own, 250 ms each), the job's derivation and merge, and, when the sync lands a leg's first movement, that leg's opening read from the chain before the verdict (the 2026-09-28 rule), a read the inline merge never made.
  • The main lane's order (N4): whole-window jobs (enrol, rederive) share the main lane with continuous ones, ahead of them by priority, so a whale's enrolment holds every other wallet's continuous jobs for as long as it runs: their stamps wait meanwhile, and past 30 minutes the queue-age term pages. Before this release the drain's child ran that work beside the worker, under its 30-minute kill. A gap-patch replay that runs again no longer queues a second enrolment: it widens the wallet's queued one. A second lane for whole-window jobs is the lever if real enrolments make the wait matter.
  • Connections: the worker opens up to seven for its two lanes (four before this release), one for its lock, and up to PG_POOL_MAX (12 by default) through the shared pool the mark reads use: up to 20 on prod, beside the app's and the crons'. On staging a hand-run with PG_POOL_MAX=4 stays at 12 of the role's 20.
  • The fence's cost: two fingerprint reads per tick-range job, 0.63 ms each at the fixture's largest wallet (41 rows) and about 38 ms at 100,000 rows (measured for this release); noise at today's population. A per-wallet ledger version that every writer bumps is the constant-time form, owed before a whale.
  • The Dune budget: every derivation's mirror fetch-throughs now spend the worker's one rolling day (external dependencies).
  • The offline history builder stays a direct writer, so a history build keeps base defect 5's mirrored order open while it runs, as it did before this release.
  • Staging has no standing worker (a decision for Fred): after this release staging's page loads report derivation-pending and its registrations' ledgers wait until a hand-run. A standing staging worker (a second pm2 process from the staging checkout) would make staging behave like prod, at the cost of a process beside prod's on the box and up to twelve of the staging role's twenty connections.

What step 2 still needed (issue #981, step 2), all done by step 2 (one reviewed change, migration 129; shipped 2026-10-04 in v0.76.0, 129 run on prod at 09:05Z):

  • Drop value_market / value_redemption (DESTRUCTIVE, hand-run), once the census (scripts/ops/value-parity.ts --db-url) reports no row served stored and the reconciler's factless=0/0/0: done by step 2. The two-class decision this needed is closed (Fred, 2026-10-02; migration 128, its entry): a reading keeps every rate its value read, so a two-level chain-rated composition and a PT over a composed payout asset are computed from their own facts and the writers produce no reading served stored for want of one. What can still hold the count above zero is a row written before 128 (the owner's wipe removes them), a PT movement with no stamp, a pre-window fill stored without its consideration.
  • Delete the old derivation call sites behind WORKER_OWNS_DERIVATION (the page load's inline merge, the replay's, the tick's per-wallet pass, the trigger's inline launch), the constant, the worker's pre-flip branches (handMadeKindRefusal, sweepOwnsTick's false arm, sweepNotOwnedLine) and the restart script's warning arm for a missing worker: done by step 2.
  • Delete the W9 / W10 residue: done by step 2.
  • Lift the coverage restatement's ether hold (issue #989, PR #996): done by step 2. In the same change that drops the two columns, delete the ether-book branch of startPass in src/lib/portfolio/coverage-restatement.ts (and flip its fixture cell, ETHER, to a restatement). Until then every EXCLUDED -> ETH widening is held whole, on one line per asset at every pass: the reading audit reads those frozen dollar columns against the ether dust floor (the coverage restatement).

Not step 2's, and still carried: S8c's decision, the per-wallet ledger version, the capacity and soak items, and the history builder's mirrored order (the contract list).

eUSDe becomes redemption-priced (migration 123): prod steps, in order ​

  • belongs to: issue #987 (PR #997, branch fix/eusde-redemption-priced), migration 123
  • executed: 2026-10-02

v0.75.0 (release PR #1005, merge 1bb76faf, deployed 20:04Z; integration fix #1006). Step 1: eUSDe 37 readings (wallet, chain), no Pendle market, 0 flow/fill rows; census before served stored (no rate fact) 0 on every line kind. Step 2: 123 by hand 13:59Z, row as expected. Step 4: hand refresh-assets 20:26Z, share-rate row 1.0000000000099645, newest bar 2026-10-02 10:00 (stopped). Step 5: 180 row(s) written in 4 statement(s), 1 kept, 0 failed; 181 of 181 boundaries, share_rate 1.0000000000099645, re-run nothing to write. Step 6: 0x0b49… served stored (no rate fact) 0, eUSDe market lines differ by the pool discount (max 2.0%). Step 7: census after served stored (no rate fact) 0 on every line kind.

What it changes for a user, in one line: a wallet holding eUSDe is valued at eUSDe's redemption rate times USDe's price on both lines, so its total-return line sits on its accrual line instead of following a thin pool's prints, and the APY beside a bare eUSDe holding reads 0.00% (its rate is flat on chain) instead of a dash. Expand only: one registry row amended and one token added to the yields refresher's list; nothing is deleted and no stored row is rewritten.

Decided (Fred, 2026-09-29; recorded in issue #987). eUSDe moves from Market-priced to Redemption-priced under the settled test: a token is redemption-priced when at least $5M can be minted AND redeemed atomically both ways, OR when no real DEX market exists (20 of the last 30 days traded, a $100k median daily volume, one $1M pool). eUSDe fails every bar of the market test (about $1 median daily volume, a top pool of about $12.5k, 15 to 16 of 30 trading days) and its instant redemption is about $1.6M. Applied by this release ahead of the fourteen-day proposal, which would have reached the alert line around 2026-10-07.

What it does NOT need. No re-mark (scripts/repair/remark-snapshot-marks.ts is the tool from before migration 116 and is not run): values are computed at read from each stored row's facts, so the registry edit re-values eUSDe's whole stored history on the first read after the processes restart. No wallet wipe, no re-derive, and no backfill of price bars: eUSDe's stored bars stay in the table and are read by nothing (the DefiLlama-only hours among them, PR #985's follow-up, included). Staging needs nothing by hand: its deploy applies the additive 123, and its nightly reseed restores prod's database, so the rate-series backfill (step 5) is a prod step only.

  1. Read-only checks, before anything (prod). The row as it stands, every stored eUSDe leg and the rate fact each carries, and any Pendle market that pays out in eUSDe:

    sql
    -- read-only
    SELECT symbol, valuation, feed, liquidity, underlying_address, mint_terms, redeem_terms, capacity_reader
      FROM onchain_credit.portfolio_tokens
     WHERE chain_id = 1 AND address = '0x90d2af7d622ca3141efa4d8f1f24d86e5974cc8f';
    SELECT venue, rate_source, count(*) AS readings, count(DISTINCT wallet) AS wallets
      FROM onchain_credit.portfolio_position_snapshots
     WHERE chain_id = 1 AND accounting_asset = '0x90d2af7d622ca3141efa4d8f1f24d86e5974cc8f'
     GROUP BY 1, 2 ORDER BY 1, 2;
    SELECT pt_address, name, maturity_ts, status
      FROM onchain_credit.pendle_markets
     WHERE chain_id = 1 AND underlying_address = '0x90d2af7d622ca3141efa4d8f1f24d86e5974cc8f';
    -- the movements and pre-window PT fills valued at what was paid in eUSDe that kept no eUSDe rate
    SELECT 'flow' AS rel, kind, meta->>'valuationBasis' AS basis, count(*) AS rows, count(DISTINCT wallet) AS wallets
      FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND consideration_asset = '0x90d2af7d622ca3141efa4d8f1f24d86e5974cc8f'
       AND NOT (coalesce(meta->'rateFacts', '{}'::jsonb) ? '0x90d2af7d622ca3141efa4d8f1f24d86e5974cc8f')
     GROUP BY 1, 2, 3
    UNION ALL
    SELECT 'fill', NULL, NULL, count(*), count(DISTINCT wallet)
      FROM onchain_credit.portfolio_pt_prewindow_fills
     WHERE chain_id = 1 AND consideration_asset = '0x90d2af7d622ca3141efa4d8f1f24d86e5974cc8f'
       AND NOT (coalesce(rate_facts, '{}'::jsonb) ? '0x90d2af7d622ca3141efa4d8f1f24d86e5974cc8f');

    Expect eUSDe|market|dune_tape|secondary|0x4c9e…68b3|instant|instant|erc4626; every eUSDe reading, on whatever venue holds it (a bare balance, an Aave supply, a collateral posting), with rate_source = 'chain', the fact BOTH lines read after the move, so no such reading stops being computed; no Pendle market, or only matured ones nobody holds; and no flow or fill row (eUSDe trades about $1 a day). What turns served stored under the move is every row whose market line is valued in eUSDe while its redemption line does not read eUSDe's rate, because before 123 that market line read a bar and its writer kept no eUSDe fact: a PT whose payout is eUSDe (the pendle venue in the second query, or a PT of the third posted as collateral), and a movement or pre-window fill valued at what was paid in eUSDe (a swap out of it, a Pendle buy with it, a payment across books), which the fourth query counts; a row whose redemption line already read eUSDe carries the fact and drops out of the count. Such a row changes no number while the stored columns exist (it is served them), and the rate-facts backfill cannot rescue it (it fills only a fact that reproduces the stored value, and a value struck at the pool's bar is not rate x USDe). If any count is non-zero, name the wallets in the release PR: before the contract release's step 2 drops the stored columns (it is gated on factless=0/0/0), Fred decides whether those rows keep their stored values, the same call as the two classes no fact column holds (what step 2 still needs). Then record the census baseline, served stored (no rate fact) per line kind:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    npx tsx scripts/ops/value-parity.ts --db-url "$DATABASE_URL" | tee /tmp/eusde-census-before.log
  2. Migration 123, BY HAND, BEFORE the deploy, from the staging checkout (the 119 pattern): the row exists, so the database's answer wins over the compiled seed, and every long-running process reads the registry once, at start. Applied first, the deploy's own restarts load it. It is safe for the previous release, which already values a composed row with an underlying and no feed exactly as this one does.

    bash
    git -C /opt/onchain-credit-staging rev-parse HEAD                      # = the release PR's head commit
    git -C /opt/onchain-credit-staging status --porcelain -- scripts/sql   # prints nothing
    f=123-eusde-redemption-priced
    sudo -u postgres env "PGOPTIONS=-clock_timeout=10s -cstatement_timeout=300s" \
      psql -v ON_ERROR_STOP=1 -X -q -1 -d creddit -f /opt/onchain-credit-staging/scripts/sql/$f.sql \
    && sudo -u postgres psql -q -d creddit -c "INSERT INTO onchain_credit.schema_migrations(filename) \
         VALUES ('$f.sql') ON CONFLICT DO NOTHING"
    sudo -u postgres psql -d creddit -At -c "SELECT symbol, status, wallet_tracked, book, class, valuation, feed, underlying_address, rate_kind, rate_getter, liquidity, liquidity_verified, mint_terms, redeem_terms, capacity_reader FROM onchain_credit.portfolio_tokens WHERE chain_id = 1 AND address = '0x90d2af7d622ca3141efa4d8f1f24d86e5974cc8f'"

    Expect:

    text
    eUSDe|active|t|USD|variable_rate|composed||0x4c9edd5852cd905f086c759e8383e09bff1e68b3|getter|{"kind": "erc4626", "divisorPow10": 18}|primary_buffer|2026-10-01|instant|instant|erc4626

    If this step is taken AFTER the deploy instead, migrate.sh from /opt/onchain-credit applies it, and the app, the ingester and the ledger worker must then be restarted (the restart rule); until they are, they value eUSDe the old way.

  3. The deploy (merge staging into main). From the first process start the yields refresher's list carries eUSDe.

  4. The first six-hourly refresh-assets tick after the deploy (or a hand run once the deploy has finished, never during it: scripts/run-cron.sh refresh-assets.ts). Check, rather than reading counts off the log:

    • eUSDe's first share-rate row: SELECT snapshot_ts, share_rate, supply_apy, apy_30d, block_at_snapshot FROM onchain_credit.token_yield_apy WHERE token_address = '0x90d2af7d622ca3141efa4d8f1f24d86e5974cc8f' ORDER BY snapshot_ts DESC LIMIT 3 returns a fresh row at about 1.00000000001 (no [token-yields/fail] … eUSDe line);
    • eUSDe has left the price-bar sync: its newest bar (SELECT max(bar_ts) FROM onchain_credit.token_price_bars WHERE chain_id = 1 AND token_address = '0x90d2af7d622ca3141efa4d8f1f24d86e5974cc8f') stops advancing, and no dark-feed or vendor line names it;
    • the pricing leg still reads eUSDe's capacity through erc4626 and proposes nothing for it: its candidate and its declared category now agree;
    • no [fail] or [partial] line names eUSDe.
  5. The trailing window of eUSDe's rate series: a prod write, NEEDS THE OWNER'S GO. The series is what a writer falls back to when its on-chain read of eUSDe's rate does not answer, so a re-derivation or a newly enrolled wallet replaying the last thirty days needs it filled behind the release (the runner). Read-only plan first:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    T=0x90d2af7d622ca3141efa4d8f1f24d86e5974cc8f
    npx tsx scripts/ops/backfill-token-rate-series.ts --db-url "$DATABASE_URL" --token $T --plan

    Expect a 45-day window of 181 six-hourly boundaries, the rows the live refresher has already written kept, the rest to write, and their blocks "taken from the refresher's own rows" (a boundary a missed tick left with no row for any token is resolved by timestamp instead). With the owner's go:

    bash
    npx tsx scripts/ops/backfill-token-rate-series.ts --db-url "$DATABASE_URL" --token $T --execute | tee /tmp/eusde-rate-series.log
    npx tsx scripts/ops/backfill-token-rate-series.ts --db-url "$DATABASE_URL" --token $T --execute | tail -1   # nothing to write

    Expect 0 failed and share_rate 1.0000000000099… .. 1.0000000000099… (the rate is flat on chain: the same window, run against a scratch database on 2026-10-01, read 1.0000000000099645 at all 181 boundaries), then nothing to write. A non-zero exit names each boundary it could not read; running it again fills only those. Record the summary line here.

  6. The acceptance wallet, 0x0b49f0149bc0aed0b4ea9df8886cfb2c75f74d62 (added by Fred on 2026-10-01: about 99,968 eUSDe and dust ETH, untouched since February 2025). After steps 2 to 5, its USD total-return line sits on its accrual line across the whole 30-day window: eUSDe is worth one USDe per share times USDe's price, so the two lines part only by USDe's own distance from a dollar, a few hundredths of a percent at most. Before the release the total-return line followed the thin pool's tape, whose accepted bars ran from 0.979 to 1.0006 over the last 30 days (source dune:prices.hour). On the page: the USD view's two lines coincide, and the eUSDe row shows its market and redemption values apart by no more than USDe's own distance from a dollar, at entry as today. Read-only on the box:

    bash
    npx tsx scripts/ops/value-parity.ts --db-url "$DATABASE_URL" --wallets 0x0b49f0149bc0aed0b4ea9df8886cfb2c75f74d62

    Every eUSDe reading computes (served stored (no rate fact) 0); its redemption line equals the stored column, and its market line differs from it by the pool's discount, which is the move rather than a finding (the stored column was struck at the pool's bar and is unread).

  7. The census after (read-only, the step 1 command again, to /tmp/eusde-census-after.log): served stored (no rate fact) unchanged on every line kind, which is the precondition the contract release's step 2 watches (what step 2 still needs); eUSDe's market lines now count under differs, as step 6 explains. A row that turned served stored is one step 1 counted: a PT whose payout is eUSDe, or a movement or pre-window fill valued at what was paid in eUSDe whose redemption line does not read eUSDe's rate. Name it for Fred, for the decision step 1 describes.

The registration wait and the reading top-up (issue #991): prod steps, in order ​

  • belongs to: issue #991 as re-scoped on 2026-10-01 (PR #998, branch fix/replay-waits-for-wallet-certification); no migration
  • executed: 2026-10-02

v0.75.0 (release PR #1005, merge 1bb76faf, deployed 20:04Z; integration fix #1006). Plan: 226 readings over 18 legs on 6 wallets (0xe51d…, 0xaae6…, 0xb47c…, 0xb8b8…, 0xe159…, 0xef08…), no REFUSED. Canary 0xe51d…: 87 of 87, rederive #711 done; withholdsByShape W1 4 → 2 (the dust rUSD leg 5e-7 at two 6h-tick readings, 26049208/26050994, which the top-up does not re-read by design). Batch of five: 139 of 139, rederives #713–#717 done, audits #718–#722 done. Idempotency run: owed 0.

What it changes for a user, in one line: a wallet that registers stays in the building state a minute or two longer (until its own transfer history is certified), and then its past chart holds every token it sold before it registered; the wallets built before this release get those past readings once, so their past daily book value includes those tokens.

What it does, and what it leaves.

  • The registration wait (data-pipeline): the minutely drain does not start a FRESH build whose wallet's own wallet-token certificate is short of its window start. It prints [registration-wait] N of M queued registration build(s) wait for their wallet's own transfer history … while one waits, leaves the row queued in its place with no attempt spent, and writes the replay deferral marker, so the drain's [v2-deferred] scan names the wait past its hour and the 6h reconciliation alarm pages the wallet with its age and cause, as for every deferral. A build that starts anyway prints [registration-wait] 0x… registration build WAITS … and [backfill] WAITING …, exits 75, and the drain's summary says , K re-queued to wait for their own transfer history. No migration, no crontab change, no new process; the exit code of the drain is unchanged (a wait never pages from it).
  • The reading top-up (data-pipeline), scripts/ops/topup-unread-readings.ts: for every wallet built before, the past readings of its replay grid where the ledger holds a WALLET TOKEN (wallet:token:<token>) and no row reads it, read at each reading's own block through the replay's own read, stored as the replay stores them, and one rederive per wallet queued with them (its re-audit compares the new rows). Wallet tokens alone, because the race could hide only what the wallet's own transfer history certifies: a venue leg the ledger holds and a replay reading omits has another cause, and re-read today it could land in a past reading under a key the reading's other rows do not use (a Fluid smart side between issue #990's release and its restatement: the side counted twice). A plan that names any other leg prints it REFUSED and exits 2, and the execution never reads or writes that wallet. Plan by default (read-only), --execute to write. A data step on prod: it needs the owner's go, even though the fix itself is approved.
  • The reconciler's hand-run --json gains withholdsByShape per wallet (W1 unread-endpoint → n), which is how steps 3 and 7 read one wallet's W1 stretches.

With issue #990 in the same release (PR #1000, its entry), the top-up waits for that release's restatement: steps 3 to 8 below start only after #990's step 7, which comes after its restatement has committed with no HELD BACK wallet and the worker has drained the restatement's rederive and audit jobs (the order). Run before it, each rederive the top-up queues re-derives the wallet's smart side in shares while its readings still hold it per token. Shipped in different releases: run the top-up, and drain every job it queued, before #990's deploy, or after #990's step 7.

Staging, before the release ​

Staging runs no worker and no ingester, so this is an attended hand-run from the staging checkout, one at a time (PG_POOL_MAX=4), and nothing here names pm2 or touches creddit.

0. The shell, read rather than assumed: this PR merged into staging and deployed.

bash
cd /opt/onchain-credit-staging
set -a; . ./.env.local; set +a
printf '%s\n' "$DATABASE_URL" | grep -c '/creddit_staging'   # 1
umask 077

1. The wait is inert on staging, and that is the check. The reseed's scrub deletes the wallet-token rollout marker, so no registration on staging waits: a sign-in there builds as before, and the drain's log holds no [registration-wait] line. (The wait itself is pinned on the fixture, scripts/ops/topup-unread-readings.test.ts, THE WAIT.)

bash
grep -c 'registration-wait' /tmp/onchain-credit-cron/onchain-credit-staging-drain-portfolio-backfills.log   # 0

2. The top-up over a hole made on purpose, because staging holds none of prod's: after the reseed it holds only the wallets registered on it since (Fred's sign-in). Take one such wallet W whose build is done, and one wallet-token leg L it held over its replay readings; keep a copy of those readings, delete them (staging only), and let the top-up put them back from the chain:

Three preconditions, read before anything is deleted, or the rehearsal plans less than it deletes for a reason the diff below does not give. Staging runs no worker: a wallet registered since the reseed may still have its enrol queued and no derive cursor, and the top-up skips such a wallet as "not derived yet" (run the bounded worker hand-run below first, then read again).

bash
: "${W:?}" "${L:?}"   # e.g. L=wallet:token:0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48
# (a) W's history is derived: 1 (0: the bounded worker hand-run below first)
sudo -u postgres psql -d creddit_staging -At -c "SELECT count(*) FROM onchain_credit.chain_scan_cursors WHERE chain_id = 1 AND scope = 'portfolio:derive:v2:1:$W'"
# (b) the ledger holds L at every one of those readings: the two numbers are equal
sudo -u postgres psql -d creddit_staging -At -c "SELECT count(*) FILTER (WHERE h.to_balance > 0), count(*) FROM onchain_credit.portfolio_position_snapshots s LEFT JOIN LATERAL (SELECT f.to_balance FROM onchain_credit.portfolio_flow_events_v2 f WHERE f.chain_id = 1 AND f.wallet = s.wallet AND f.venue = 'wallet' AND f.position_key = s.position_key AND f.block_number <= s.block_number ORDER BY f.block_number DESC, f.log_index DESC, f.seq DESC, f.tx_hash DESC LIMIT 1) h ON true WHERE s.chain_id = 1 AND s.wallet = '$W' AND s.position_key = '$L' AND s.basis = 'backfill'"
# (c) L is never the only leg of one of those readings (deleting it would delete the reading): 0
sudo -u postgres psql -d creddit_staging -At -c "SELECT count(*) FROM onchain_credit.portfolio_position_snapshots s WHERE s.chain_id = 1 AND s.wallet = '$W' AND s.position_key = '$L' AND s.basis = 'backfill' AND NOT EXISTS (SELECT 1 FROM onchain_credit.portfolio_position_snapshots o WHERE o.chain_id = 1 AND o.wallet = s.wallet AND o.snapshot_ts = s.snapshot_ts AND o.position_key <> s.position_key)"

Then keep a copy, delete, plan, execute, compare:

bash
sudo -u postgres psql -d creddit_staging -c "\copy (SELECT snapshot_ts, block_number, qty_raw FROM onchain_credit.portfolio_position_snapshots WHERE chain_id = 1 AND wallet = '$W' AND position_key = '$L' AND basis = 'backfill' ORDER BY snapshot_ts) TO '/tmp/topup-staging-before.csv' CSV"
wc -l /tmp/topup-staging-before.csv
sudo -u postgres psql -d creddit_staging -c "DELETE FROM onchain_credit.portfolio_position_snapshots WHERE chain_id = 1 AND wallet = '$W' AND position_key = '$L' AND basis = 'backfill'"
npx tsx scripts/ops/topup-unread-readings.ts --db-url "$DATABASE_URL" --wallets "$W" | tee /tmp/topup-staging-plan.log
DUNE_MAX_CREDITS_PER_RUN=0 npx tsx scripts/ops/topup-unread-readings.ts --db-url "$DATABASE_URL" --wallets "$W" --execute | tee /tmp/topup-staging-execute.log
sudo -u postgres psql -d creddit_staging -c "\copy (SELECT snapshot_ts, block_number, qty_raw FROM onchain_credit.portfolio_position_snapshots WHERE chain_id = 1 AND wallet = '$W' AND position_key = '$L' AND basis = 'backfill' ORDER BY snapshot_ts) TO '/tmp/topup-staging-after.csv' CSV"
diff /tmp/topup-staging-before.csv /tmp/topup-staging-after.csv && echo identical
DUNE_MAX_CREDITS_PER_RUN=0 npx tsx scripts/ops/topup-unread-readings.ts --db-url "$DATABASE_URL" --wallets "$W" --execute | tail -1

The plan names one stretch of L, as many readings as the copy holds (fewer only where the ledger holds L at none of a reading's block, which the plan's line states); the execution's line reads wrote W: N of N owed reading row(s); rederive job #… queued over [F,T]; the diff prints identical (the replay's own read at the replay's own blocks restores what the replay wrote), and the second run reads owed 0 …; written 0; … rederives queued 0. Then drain the queued rederive and the audit it queues with a bounded hand-run:

bash
LEDGER_WORKER_EXIT_WHEN_IDLE=1 PG_POOL_MAX=4 timeout 1800 bash scripts/worker/run-worker.sh 2>&1 | tee /tmp/staging-topup-worker-$(date -u +%FT%H%M%SZ).log
sudo -u postgres psql -d creddit_staging -c "SELECT kind, state, left(coalesce(error, ''), 120) FROM onchain_credit.portfolio_derive_jobs WHERE chain_id = 1 AND wallet = '$W' AND created_at > now() - interval '1 hour' ORDER BY id"

Expected: the rederive done, the audit after it done (not partial). Optionally, a plan over the whole staging population (--db-url "$DATABASE_URL" alone) shows what else staging owes.

Prod steps, in order ​

1. Deploy (the release PR's merge). Nothing else: no migration, no crontab line, and the worker restarts with the deploy as on every release. (With issue #990 in the same release the worker is stopped across the deploy instead, and steps 3 to 8 wait for #990's step 7: the order.)

2. The first registration after it, whenever one comes: the drain's log shows the wait for about as long as the wallet's catch-up takes (two minutes for 0xe51d… on 2026-09-24), then the build; its historical discovery line counts no wallet-token row below its certificate any more.

bash
L=/tmp/onchain-credit-cron
grep -E 'registration-wait|historical discovery|WAITING' $L/onchain-credit-drain-portfolio-backfills.log | tail -8

3. Before (read-only): 0xe51d…'s history as the page reads it, and its W1 count.

bash
cd /opt/onchain-credit
set -a; . ./.env.local; set +a
E=0xe51d05913b0951cf8b48596274bd086efdcc3ed9
npx tsx scripts/ops/golden-portfolio.ts --db-url "$DATABASE_URL" --wallets $E --surfaces history --out /tmp/topup-e51d-before
npx tsx scripts/ops/reconcile-ledger.ts --wallet $E --json 2>/dev/null | jq '.reports[] | select(.scope == "wallet") | .withholdsByShape'

4. The top-up's plan (read-only: nothing read from the chain, nothing written):

bash
npx tsx scripts/ops/topup-unread-readings.ts --db-url "$DATABASE_URL" | tee /tmp/topup-readings-plan.log
tail -1 /tmp/topup-readings-plan.log
grep -F "$E" /tmp/topup-readings-plan.log

Expected for 0xe51d…: one owed stretch each for wallet:token:0x6c3ea9036406852006290770bedfcaba0e23a0e8 (PYUSD) and wallet:token:0x8292bb45bf1ee4d140127049757c2e0ff06317ed (RLUSD) from 2026-08-25 to 2026-09-12, and wallet:token:0xf939e0a03fb07f59a73314e73794be0e57ac1b4e (crvUSD) from 2026-08-25 to 2026-09-06, each the daily readings before its exit, with the ledger's raw balance at the first (about 21.35 PYUSD, 35.65 RLUSD and 3.21 crvUSD, in the tokens' smallest units). The other wallets the 2026-09-28 re-audits reported unread (the window-start repair, step 3: 0xaae6…, 0xb47c…, 0xb8b8…, 0xe159…, 0xef08…) appear with their own stretches. Stop if a line names a wallet those re-audits did not, other than one registered since, and stop if a line reads REFUSED (a leg that is not a wallet token; the plan then exits 2): read why before writing anything.

5. The top-up — NEEDS THE OWNER'S GO. Production's ETHEREUM_RPC_URL serves past blocks (the script routes ETHEREUM_ARCHIVE_RPC_URL first where it is set, as the registration CLI does). DUNE_MAX_CREDITS_PER_RUN=0: the stored value columns are read only for a reading without its rate facts, which the replay's writer always states, and they go in #981 step 2, so a price bar missing at a past hour costs nothing a page shows, and the run spends no Dune credit. It is a prod write over every built wallet, and each wallet it writes queues a whole-window rederive on the worker's main lane, so it goes in pieces. The CLI has no --limit or --batch flag: --wallets is the only bound.

5a. The canary: 0xe51d… alone, then step 6's job check and step 7 for it, before any other wallet.

bash
DUNE_MAX_CREDITS_PER_RUN=0 npx tsx scripts/ops/topup-unread-readings.ts --db-url "$DATABASE_URL" --wallets $E --execute | tee /tmp/topup-readings-execute.log
tail -1 /tmp/topup-readings-execute.log

5b. The rest: the other wallets step 4 named, in lists of five or fewer, each list followed by step 6's job check before the next. Then one run over the whole population, which must find nothing left:

bash
B=0x…,0x…   # at most five wallets from step 4's plan
DUNE_MAX_CREDITS_PER_RUN=0 npx tsx scripts/ops/topup-unread-readings.ts --db-url "$DATABASE_URL" --wallets "$B" --execute | tee -a /tmp/topup-readings-execute.log
grep -E 'wrote|not stated|NOT topped up|skipped|REFUSED' /tmp/topup-readings-execute.log
# after the last list: the idempotency run, over every wallet
DUNE_MAX_CREDITS_PER_RUN=0 npx tsx scripts/ops/topup-unread-readings.ts --db-url "$DATABASE_URL" --execute | tail -1

Expected: one wrote 0x…: N of N owed reading row(s); rederive job #… queued over [F,T] per wallet the plan named, not stated 0 (the 2026-09-28 re-audits read these legs directly and found them held), wallets failed 0, skipped under the lock 0, refused 0; the last run owed 0 …; written 0; … rederives queued 0. Stop at the first NOT topped up, not stated, skipped under the lock or REFUSED line, at an exit other than 0, and at a partial audit in step 6, and read why before the next list. (A not stated line is a leg the chain did not show held at that reading: nothing was stored for it, and the audit of that reading books the exit or reports it. A NOT topped up wallet wrote nothing and is re-read whole by the next run.)

6. The worker drains the rederive jobs and the audits each queues (pm2 creddit-ledger-worker; nothing to start). Read this after the canary and after every list of step 5b:

bash
sudo -u postgres psql -d creddit -c "SELECT wallet, kind, state, left(coalesce(error, ''), 140) FROM onchain_credit.portfolio_derive_jobs WHERE chain_id = 1 AND kind IN ('rederive', 'audit') AND created_at > now() - interval '2 hours' ORDER BY id"

Every rederive done, and every audit after it done: a partial naming unread on a leg the top-up wrote is a finding.

7. Verification on 0xe51d… (the owner checks it after the release):

bash
sudo -u postgres psql -d creddit -c "
  SELECT position_key, min(snapshot_ts), max(snapshot_ts) FILTER (WHERE snapshot_ts < '2026-09-20'), count(*)
    FROM onchain_credit.portfolio_position_snapshots
   WHERE chain_id = 1 AND wallet = '$E'
     AND position_key IN ('wallet:token:0x6c3ea9036406852006290770bedfcaba0e23a0e8',
                          'wallet:token:0x8292bb45bf1ee4d140127049757c2e0ff06317ed',
                          'wallet:token:0xf939e0a03fb07f59a73314e73794be0e57ac1b4e')
   GROUP BY 1 ORDER BY 1"
npx tsx scripts/ops/golden-portfolio.ts --db-url "$DATABASE_URL" --wallets $E --surfaces history --out /tmp/topup-e51d-after
diff <(jq . /tmp/topup-e51d-before/$E/history.json) <(jq . /tmp/topup-e51d-after/$E/history.json) | head -40
npx tsx scripts/ops/reconcile-ledger.ts --wallet $E --json 2>/dev/null | jq '.reports[] | select(.scope == "wallet") | .withholdsByShape'

It holds when each token has readings from 2026-08-25 to its last daily reading before its exit (crvUSD to 2026-09-06, PYUSD and RLUSD to 2026-09-12; PYUSD also from 2026-09-28, its re-acquisition), the past daily book value from 2026-08-25 to 2026-09-12 has grown by those holdings (about $60 at the start: 21.35 PYUSD, 35.65 RLUSD, 3.21 crvUSD), and withholdsByShape names no W1 unread-endpoint (the next 6h reconciler run's withholds= for the wallet drops by the same count). Then the hourly alarm's ledger-audit arm reads ok.

8. Record here: the date in executed:, the plan's and the execution's summary lines, step 6's job counts and step 7's figures.

Rollback. Revert the release and registrations build at once again (no wait); nothing of the schema or the queue changes. The topped-up readings need no rollback: each is the chain's own balance at a reading that already stood, written as the replay writes it. To remove one wallet's by hand, delete its basis = 'backfill' rows of the topped-up legs whose updated_at is inside the execution's run (the log's start line names the instant) and queue a rederive of the wallet (the template), whose re-audit restates the readings.

The smart-side release (migration 125): prod steps, in order ​

  • belongs to: issue #990 (a Fluid smart side priced as one position in its pool's shares; PR #1000, branch feat/fluid-smart-composite-position), migration 125
  • executed: 2026-10-02

v0.75.0 (release PR #1005, merge 1bb76faf, deployed 20:04Z; integration fix #1006). 125 by hand 13:59Z; worker stopped 20:04Z before the merge. Plan/dry run: 1584 retired reading rows in 792 side readings, 27 ledger rows, 2 wallets (0xd775…, 0xe51d…); verified: 792/792, refused none. Dump /var/tmp/smart-restate-20261002T200643Z (COPY 1584 / 27 / 2). --apply: 2 restated, 0 held back, 0 failed; rederives #706/#707 done. Worker restarted 20:29Z (after the f(x) backfills and a hand refresh-assets). Openings: 1 written (dust rUSD on 0xe51d…), 112 present. Acceptance: 0 retired readings, 0 retired ledger rows; 0xe51d… files no W4.

What it changes for a user, in one line: a Fluid smart collateral or smart debt side is one row with one value and one yield per mark, its two tokens shown as its composition; the day it is entered books the pool's own cost and nothing else, and no token reports a gain or loss of its own (M35).

What it does, and what it leaves.

  • From the deploy, the reader writes each smart side as ONE reading (fluid:vault:<vault>:nft:<id>:smart:<side>, its share balance, its composition in the new composition column), and the derivation writes each smart operate and seizure as ONE ledger row in shares, valued at the pool's own token amounts (meta.poolTokens).
  • Rows written before it hold a smart side in the RETIRED per-token form (one reading row and one ledger leg per pool token). Nothing in the release rewrites them; step 5 below does. Between the deploy and step 5 a wallet holding a smart side is held in two forms: its new readings state the side in shares, its older readings and its ledger per pool token. Three rules keep that window from showing a side twice:
    • The ledger worker is stopped from just before the deploy until step 5's --apply has committed (steps 2 and 6). Nothing derives in between, so no ledger comes to state a side in shares beside readings that state it per token: no whole-window re-derivation (a rederive the reading top-up queues, a bar re-judge's) and no operate on the side is derived in the new form ahead of its restatement. Meanwhile the page serves the last derived state (a refresh reports derivation-pending, a registration waits in its building state: the stopped worker), the side keeps its retired token rows at their last reading before the deploy, their yield "not measured" from then on, and the derive-lag arm pages hourly. Take step 5 straight after the deploy.
    • The reading audit compares neither form where the two meet, in either direction: a reading in shares against a ledger per token, and a reading per token against a ledger in shares (the second is what any re-derivation under this release's code produces before the wallet is restated). Nothing is booked or paged for the side there, in particular no opening on a retired token key, which the page would serve beside the side.
    • The reading top-up of issue #991 (its entry) owes and writes wallet tokens alone, and refuses any other leg (REFUSED, exit 2), so it never re-reads a smart side into a past reading. In the same release it runs after this entry's step 7 (the order below).
  • Migration 125, expand only: a nullable composition jsonb on portfolio_position_snapshots (database). No row is written by it.

The order with issue #991's reading top-up (PR #998), when both ship in one release. This is the only safe order:

  1. this entry's steps 1 to 3: migration 125, the worker stopped and saved stopped, the deploy;
  2. steps 4 and 5: the restatement, which must end with no HELD BACK wallet;
  3. step 6: the worker started, and the restatement's rederive and audit jobs drained;
  4. step 7: the window-start openings;
  5. only then the top-up (its entry, from its step 3): its plan, a canary on 0xe51d05913b0951cf8b48596274bd086efdcc3ed9 alone, then batches of five wallets or fewer, with its job check after each.

With issue #989 in the same release (PR #996), its coverage restatement runs inside the worker, so its first pass runs at step 6's start, before the worker's first claim, and step 6 is done only once that pass has printed [restate] done: (its place in this order).

Run the other way round, each rederive the top-up queues re-derives that wallet's smart side in shares while its readings still hold it per token: the side's past then reads as unread (the audit's truce: nothing booked, nothing paged) until the restatement, which re-derives the whole window again. Shipped in different releases, the top-up and every job it queued are drained before this deploy, or the top-up waits for step 7.

A HELD BACK wallet (step 5) is not restated: its readings and its ledger stay in the retired form, untouched. Keep the worker stopped while you read why. A no-read refusal is a read that failed: run the dry run and --apply again. Anything else needs a decision before the worker starts. If the worker has to start first, keep that wallet out of the top-up (name the others with --wallets) until it is restated, and know that an operate on its side before then shows the side twice (its retired token rows at their last reading beside the side in shares) until it is.

Staging (the rehearsal, hand-runnable; no owner's go needed). The staging deploy applies 125 (migrate.sh, additive). The nightly reseed restores prod's schema without composition until 125 reaches prod, and every reading write names the column, so between a 03:00 reseed and the next staging deploy every reading write on staging fails: redeploy staging after the reseed (or touch /root/.reseed-paused across a validation window) before reading anything into a failure. The reseed's scrub empties every portfolio table, readings and ledger included, so staging holds a smart side in the retired form only where a wallet was enrolled there while staging still ran the previous release. Staging runs no standing worker, so there is nothing to stop. To rehearse step 5: pause the reseed (touch /root/.reseed-paused), register a wallet holding a smart side on staging BEFORE this release is merged to staging (its enrolment writes the retired form), let the enrolment finish, merge, then run it against creddit_staging, step 5's dump included (with -d creddit_staging), and rm -f /root/.reseed-paused after:

bash
cd /opt/onchain-credit-staging && set -a && . ./.env.local && set +a
npx tsx scripts/ops/restate-fluid-smart-sides.ts --plan-only   # counts, no chain read
npx tsx scripts/ops/restate-fluid-smart-sides.ts               # dry run: reads the archive, verifies, writes nothing
npx tsx scripts/ops/restate-fluid-smart-sides.ts --apply
# staging has no standing worker: drain the rederive and audit jobs the apply queued
LEDGER_WORKER_EXIT_WHEN_IDLE=1 bash scripts/worker/run-worker.sh

Prod, in order. Steps 1, 3, 5 and 7 write prod and need the owner's go; steps 2 and 6 stop and start the ledger worker around them.

  1. Migration 125, BY HAND, BEFORE the deploy (the new writers insert into composition and the new loader selects it from its first start, so a deploy without it fails every reading write and every page load). The release's copy of the file is the staging checkout's: confirm its commit first, as for the ledger-first release.

    bash
    git -C /opt/onchain-credit-staging rev-parse HEAD                      # = the release PR's head commit
    git -C /opt/onchain-credit-staging status --porcelain -- scripts/sql   # prints nothing
    f=125-smart-side-composition
    sudo -u postgres env "PGOPTIONS=-clock_timeout=10s -cstatement_timeout=300s" \
      psql -v ON_ERROR_STOP=1 -X -q -1 -d creddit -f /opt/onchain-credit-staging/scripts/sql/$f.sql \
    && sudo -u postgres psql -q -d creddit -c "INSERT INTO onchain_credit.schema_migrations(filename) \
         VALUES ('$f.sql') ON CONFLICT DO NOTHING"

    Check: \d onchain_credit.portfolio_position_snapshots lists composition jsonb. Idempotent; one that aborts on lock_timeout is run again when the table is quiet.

  2. Stop the ledger worker and save it stopped, right before the deploy, so that no job runs under this release's code until step 6:

    bash
    pm2 stop creddit-ledger-worker && pm2 save
    pm2 describe creddit-ledger-worker | grep status   # stopped

    The deploy leaves a stopped worker alone (its restart step prints a ::warning:: for it, the ledger worker), and a reboot inside the window keeps it stopped.

  3. The deploy (merge staging into main).

  4. Read the population (read-only, any time after the deploy):

    bash
    cd /opt/onchain-credit && set -a && . ./.env.local && set +a
    npx tsx scripts/ops/restate-fluid-smart-sides.ts --plan-only

    It prints the retired reading rows and ledger rows per wallet and the reads the restatement will make (one positionByNftId per (NFT, block) a retired reading stands at, as many getDexState per pool, one decimals() per token).

  5. GATED: the restatement, straight after the deploy. The dry run first; it reads the archive (ETHEREUM_ARCHIVE_RPC_URL) and writes nothing. Then the dump, which is what makes this step reversible (the rollback below): every retired row, and the derive cursor of every wallet that holds one, copied to the box as they stand. The worker is stopped and nothing writes the retired form any more, so the dump is exactly what --apply replaces. Each COPY n must equal step 4's counts (readings, ledger rows). Then --apply:

    bash
    npx tsx scripts/ops/restate-fluid-smart-sides.ts | tee /tmp/smart-restate-dry.log
    D=/var/tmp/smart-restate-$(date -u +%Y%m%dT%H%M%SZ); echo "$D"   # keep this path: the rollback reads it
    sudo install -d -m 700 -o postgres "$D"
    P='^fluid:vault:0x[0-9a-f]{40}:nft:[0-9]+:0x[0-9a-f]{40}:(supply|debt)$'
    R="SELECT * FROM onchain_credit.portfolio_position_snapshots WHERE chain_id = 1 AND venue = 'fluid' AND position_key ~ '$P'"
    L="SELECT * FROM onchain_credit.portfolio_flow_events_v2 WHERE chain_id = 1 AND venue = 'fluid' AND position_key ~ '$P'"
    sudo -u postgres psql -d creddit -X -v ON_ERROR_STOP=1 \
      -c "\copy ($R) TO '$D/readings.csv' CSV HEADER" \
      -c "\copy ($L) TO '$D/ledger.csv' CSV HEADER" \
      -c "\copy (SELECT c.* FROM onchain_credit.chain_scan_cursors c WHERE c.chain_id = 1 AND c.scope IN (SELECT 'portfolio:derive:v2:1:' || wallet FROM ($R) r UNION SELECT 'portfolio:derive:v2:1:' || wallet FROM ($L) l)) TO '$D/cursors.csv' CSV HEADER"
    npx tsx scripts/ops/restate-fluid-smart-sides.ts --apply | tee /tmp/smart-restate.log

    What --apply does, per wallet, in one transaction under the portfolio write lock: every retired reading is replaced by its side's one reading, read again at the reading's own block through the shipped reader and valued by the writers at the reading's moment, but ONLY where that read reproduces every stored token row to the unit; every ledger row on a retired key is deleted (movements and the audit's openings and corrections alike); the wallet's derive cursor is deleted, so every reading audit defers ("the wallet's whole history is not derived yet") instead of booking the restated side as an unexplained correction; and one whole-window rederive job is queued. STOP on a HELD BACK wallet (the run exits 2; above, "A HELD BACK wallet"): one of its readings did not restate (mismatch is a stored row the chain does not reproduce, no-read a read that failed, no-side a position the read holds no side of, mixed a reading whose rows disagree on block or basis, unreadable a retired row whose key or count does not parse). Its rows are untouched; look at the lines the report prints before anything else. A wallet whose transaction fails rolls back alone.

  6. Start the worker; it re-derives and re-audits. Only once --apply has committed with no HELD BACK wallet:

    bash
    pm2 restart creddit-ledger-worker --update-env && pm2 save

    Each rederive job writes the side's movements in the new form, stamps the cursor, and queues the re-audit of the wallet's readings, which opens the side where it was held before its window. The worker also drains what queued while it was stopped. Done when

    sql
    SELECT kind, state, count(*) FROM onchain_credit.portfolio_derive_jobs
     WHERE chain_id = 1 AND kind IN ('rederive', 'audit') AND state IN ('queued', 'running')
     GROUP BY 1, 2;   -- no row
  7. GATED: the window-start openings (idempotent, insert-only, as before): npx tsx scripts/ops/backfill-opening-rows.ts --db-url "$DATABASE_URL" (dry run), then with --apply. A smart side held at a wallet's window start is opened from its restated floor reading.

  8. Acceptance (read-only):

    sql
    -- no retired row left: both 0
    SELECT count(*) FROM onchain_credit.portfolio_position_snapshots
     WHERE chain_id = 1 AND position_key ~ '^fluid:vault:0x[0-9a-f]{40}:nft:[0-9]+:0x[0-9a-f]{40}:(supply|debt)$';
    SELECT count(*) FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND position_key ~ '^fluid:vault:0x[0-9a-f]{40}:nft:[0-9]+:0x[0-9a-f]{40}:(supply|debt)$';
    bash
    # the production case behind the issue: no W4 on the side's opening day
    npx tsx scripts/ops/reconcile-ledger.ts --wallet 0xe51d05913b0951cf8b48596274bd086efdcc3ed9 --json

    Expected on 0xe51d0591…3ed9 (NFT 19261): one smart collateral side and its USDC borrowing; the reconciler files no W4 unresolvable-composition, and the 2026-09-19 opening day books the pool's own cost on the side, about −7.21 at market and −4.46 at redemption at the opening block's composition (the figure on the wallet's own grid differs by the pool's movement up to its first reading); every later day is one accrual on the side, where the retired form swung its two token legs against each other by three figures (+$116 and −$96 between Sep 20 and 21). The positions list shows one smart collateral row with its USDC and syrupUSDC amounts.

Before issue #981's step 2. The restatement's INSERT names value_market and value_redemption, which that step drops. This entry is executed before it, and the tool (scripts/ops/restate-fluid-smart-sides.ts, its lib and its test) is deleted with that step.

Rollback. 125 stays whatever is rolled back (expand only). The code can be rolled back at any point, but never on its own: the previous release reads a …:smart:<side> key as a retired token leg named smart with the pool as its asset (EXCLUDED, unpriced, opened by its audit as a coverage start), and the six-hourly tick and the live tip write that form from the first tick after the deploy. So stop the worker and save it stopped, roll the code back (the previous release's deploy), then in ONE transaction under the portfolio write lock delete every reading and ledger row on a smart side's key, and start the worker:

  • Before step 5 that is the whole rollback: the worker was stopped from before the deploy, so no retired row was touched, and the previous release's worker continues from its cursors. The sides' readings between the deploy and the rollback are gone, so their rows show "not measured" over those hours.

  • After step 5 the same transaction also puts back what step 5 replaced, from its dump: the retired readings and ledger rows (audit rows included) and each restated wallet's derive cursor, set back to where it stood, so the previous release's worker derives everything after it again in its own form:

    bash
    D=/var/tmp/smart-restate-…   # the directory step 5 printed
    sudo -u postgres psql -d creddit -X -v ON_ERROR_STOP=1 <<SQL
    BEGIN;
    SELECT pg_advisory_xact_lock(hashtextextended('onchain_credit.portfolio_history_writers', 0));
    DELETE FROM onchain_credit.portfolio_position_snapshots
     WHERE chain_id = 1 AND venue = 'fluid' AND position_key ~ '^fluid:vault:0x[0-9a-f]{40}:nft:[0-9]+:smart:(supply|debt)\$';
    DELETE FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND venue = 'fluid' AND position_key ~ '^fluid:vault:0x[0-9a-f]{40}:nft:[0-9]+:smart:(supply|debt)\$';
    CREATE TEMP TABLE r (LIKE onchain_credit.portfolio_position_snapshots) ON COMMIT DROP;
    CREATE TEMP TABLE l (LIKE onchain_credit.portfolio_flow_events_v2) ON COMMIT DROP;
    CREATE TEMP TABLE c (LIKE onchain_credit.chain_scan_cursors) ON COMMIT DROP;
    \copy r FROM '$D/readings.csv' CSV HEADER
    \copy l FROM '$D/ledger.csv' CSV HEADER
    \copy c FROM '$D/cursors.csv' CSV HEADER
    INSERT INTO onchain_credit.portfolio_position_snapshots SELECT * FROM r ON CONFLICT DO NOTHING;
    INSERT INTO onchain_credit.portfolio_flow_events_v2 SELECT * FROM l ON CONFLICT DO NOTHING;
    INSERT INTO onchain_credit.chain_scan_cursors SELECT * FROM c
        ON CONFLICT (chain_id, scope) DO UPDATE SET last_scanned_block = EXCLUDED.last_scanned_block;
    COMMIT;
    SQL

    An error stops psql before the COMMIT (ON_ERROR_STOP), and the transaction rolls back whole. A HELD BACK wallet's rows were never deleted, so ON CONFLICT DO NOTHING leaves them as they are. Without the dump (step 5 run without it), the nightly backup is the only way back after step 5.

The coverage restatement (issue #989, migration 124): prod steps, in order ​

  • belongs to: issue #989 (the automatic restatement of readings an asset's coverage widened, and the dust floor judging a borrowing whole; PR #996, branch feat/auto-restate-covered-assets), migration 124
  • executed: 2026-10-02

v0.75.0 (release PR #1005, merge 1bb76faf, deployed 20:04Z; integration fix #1006). 124 by hand 13:59Z (index present). Plan: 46 reading(s) of 1 wallet(s) would restate EXCLUDED -> USD (0xe51d… wsrUSD), 0 held. After 126 the plan also lists 62 PT-fxSAVE readings (22 PT + 40 on the pool share) held back (rate beside its own), as the f(x) entry predicts. Worker pass 20:29Z: [restate] done: 1 asset(s) widened, 1 wallet(s) visited, 46 reading(s) restated, 62 held back, 1 carried copy restated, 0 rederive job(s) queued; wsrUSD readings USD|chain 62; no wsrUSD mover without a reading. Reconciler on 0xe51d…: book-overlays=62 (the held PT readings) factless=0/0/0.

What it changes for a user, in one line: a holding of an asset that came into coverage after it was first recorded gets its earlier history priced (its book value, its return and its accrual line over the stretch before the coverage release), the way a price repair repaints; and a borrowing worth under a cent is listed or hidden as one position, never one side of it alone (hidden whole when its collateral net of its debt is under a cent and no leg of it is worth a cent; what it booked stays in the headline).

What it does.

  • The ledger worker gains one step in its main lane, a turn at a time between claims: a pass at its first turn after every start and every six hours after, a few wallets per turn (data-pipeline): readings stored EXCLUDED whose asset the database's registry now books in dollars are restated into that book (with the rate fact a writer keeps there, and the copies audit rows carry), and each such wallet's rederive is queued in the same transaction, at most two per turn; an asset whose coverage narrowed restates nothing and is reported per asset at every pass. An ether-book widening is held whole until #981 step 2 (the reading audit reads the frozen dollar columns against the ether dust floor until they are dropped; that release lifts the hold: step 2). A Fluid smart side is judged by its pool tokens' book (issue #990) and never restated. On demand: scripts/ops/restate-covered-readings.ts (the procedure). So the worker writes prod data by itself at its first start on this release: its first turns restate what disagrees on prod at that moment. In this release that start is #1000's step 6, not the deploy (the order). Merging the release is the owner's go for that write; step 2 below shows exactly what it will be, read-only, beforehand.
  • The served positions and the All view's value line judge a financed position whole under the one-cent floor (data-pipeline). Read-only, no data.
  • Migration 124, an index only: (chain_id, accounting_asset, book, wallet) on the readings, replacing 059's (chain_id, accounting_asset) (a prefix of it). The previous release runs unchanged on it.

Expected on prod (read 2026-10-01): wallet 0xe51d05913b0951cf8b48596274bd086efdcc3ed9, whose 46 readings of its wsrUSD/AUSD Morpho borrowing (2026-08-25 to 2026-09-28) were written EXCLUDED before migration 119 covered wsrUSD, and which the reconciler prints as book-overlays=46 book-withheld=1: 46 readings restated EXCLUDED -> USD, one rederive of the wallet queued and run, and after it book-overlays=0 book-withheld=0 on its reconciler line. The USD view's total-return line for it gains the stretch from 2026-08-25 to the coverage release. Its $0.002 wsrUSD collateral and $0.002 AUSD debt, dust as a whole, are hidden together: neither leg in the positions rows, under Not covered or in its count, nor on the All view's line at that point; the USD view's headline keeps what the borrowing booked.

The order with the other three PRs of this release ​

#997 (eUSDe), #998 (the registration wait and the reading top-up) and #1000 (the smart sides) ship in the same release. #1000's entry sets the order across #998 and #1000; this entry's steps take these places in it, so the release runs one sequence:

  1. Before the deploy, by hand: #997's read-only checks and migration 123 (its steps 1 and 2); this entry's step 1, migration 124, between ticks (its index build holds writes to the readings for up to a minute); #1000's migration 125 (its step 1). The three files are independent of each other. Then this entry's step 2, the read-only plan (after 124, so its detector reads the index).
  2. #1000's step 2 (the worker stopped and saved stopped), the deploy (#1000's step 3, which is this entry's step 3), #1000's steps 4 and 5 (the smart-side restatement, ending with no HELD BACK wallet). The coverage restatement does not run in this window: it runs in the worker, which is stopped. Never run restate-covered-readings.ts --execute by hand in this release: the worker's pass does it.
  3. #1000's step 6, the worker started: the coverage restatement's first pass runs at its first turn, before the worker's first claim, so before the smart-side restatement's re-derivations run. A wallet both restatements touch (0xe51d…: the wsrUSD borrowing here, NFT 19261 there) is restated by this pass and given no second job: its line reads a whole-window job of this wallet is already open; it derives the restated history, and #1000's rederive, queued by its step 5, derives the wallet after this pass has committed. Read this entry's step 3 here. #1000's step 6 is done when the [restate] done: line is printed AND no rederive or audit is queued or running (this pass's jobs drain with #1000's).
  4. #1000's steps 7 and 8 (the window-start openings, its acceptance), and this entry's step 4 at the next reconciler run after them.
  5. Only then #998's top-up (from its step 3), its canary 0xe51d… first: its before-and-after capture of the wallet's history then shows the top-up alone, because this pass has already restated the wallet's wsrUSD history and #1000 its smart side.
  6. #997's steps 4 to 7 (the first refresh tick, eUSDe's rate series, its acceptance wallet, the census after) keep their own clock; nothing here waits for them. eUSDe's coverage does not change (its book is USD before and after 123), so the restatement finds nothing for it.

Shipped alone, the order is this entry's steps as written: the deploy restarts the worker, and its first turns restate.

Prod steps, in order ​

  1. Migration 124, BY HAND, BEFORE the merge, from the staging checkout at the release PR's head (the 122 pattern). An index build on the readings (about 100 MB on prod): writes to them wait for the build (seconds to a minute), so run it between ticks.

    bash
    git -C /opt/onchain-credit-staging rev-parse HEAD                      # = the release PR's head commit
    git -C /opt/onchain-credit-staging status --porcelain -- scripts/sql   # prints nothing
    f=124-snapshot-asset-book-index
    sudo -u postgres env "PGOPTIONS=-clock_timeout=10s -cstatement_timeout=300s" \
      psql -v ON_ERROR_STOP=1 -X -q -1 -d creddit -f /opt/onchain-credit-staging/scripts/sql/$f.sql \
    && sudo -u postgres psql -q -d creddit -c "INSERT INTO onchain_credit.schema_migrations(filename) \
         VALUES ('$f.sql') ON CONFLICT DO NOTHING"
    sudo -u postgres psql -At -d creddit -c "SELECT count(*) FROM onchain_credit.schema_migrations WHERE filename = '$f.sql'"   # 1
    sudo -u postgres psql -At -d creddit -c "SELECT indexname FROM pg_indexes WHERE schemaname = 'onchain_credit' AND tablename = 'portfolio_position_snapshots' AND indexname IN ('portfolio_pos_asset_book_wallet_idx', 'portfolio_pos_accounting_asset_idx')"
    # portfolio_pos_asset_book_wallet_idx alone

    One that aborts on lock_timeout is run again when quiet. Skipped, the release still works: the restatement's statements read the readings in full instead of the index (slower, the same answer).

  2. The plan, READ-ONLY, before the merge, from the staging checkout (it has the release's code) against prod's database, so what the deploy will write is known first:

    bash
    cd /opt/onchain-credit-staging
    # prod's environment in a subshell (its database, its archive endpoint), the release's code; --plan writes nothing
    ( set -a && . /opt/onchain-credit/.env.local && set +a && \
      npx tsx scripts/ops/restate-covered-readings.ts --plan --db-url "$DATABASE_URL" )

    Expect [restate] 0xe51d… wsrUSD (0xd3fd…3094): 46 reading(s) would restate EXCLUDED -> USD, 2026-08-25 00:00Z -> 2026-09-28 18:00Z, the asset's line 46 reading(s) of 1 wallet(s) would restate … with nothing held back, and its summary. Nothing held, because the restatement reads wsrUSD's rate getter at each reading's OWN block through the archive endpoint, and the getter answers at every block since the vault's deployment (before 2026-08-25: the wallet held it then); a held back, left EXCLUDED: <n> no redemption rate at its block means the archive endpoint did not answer there and the series did not reach back, so re-run the plan before merging. Any other would restate line is another asset whose coverage widened with a holder: it is restated too, so read it. A held back … (-> ETH) line is an ether-book widening, held by design until #981 step 2: note it for that release. Any NOT restated (coverage narrowed) line is history the registry no longer books the way it was written, reported per asset at every pass from now on; nothing is done to it. Before the deploy prod's smart sides are still in the retired per-token form: a reading held as a Fluid smart side's leg in the retired per-token form is one #1000's step 5 replaces, and it is gone by the time the worker's pass runs. A held back the Fluid smart pool … line cannot appear before #1000's restatement (no side is stored in shares yet).

  3. Merge the release PR (staging into main), then the worker's start (the prod write: needs the owner's go, which the merge is). In this release the worker is stopped across the deploy and #1000's restatement, and this pass runs when #1000's step 6 starts it (the order); shipped alone, the deploy restarts it. Its first turns restate what step 2 listed, two wallets' re-derivations per turn (one wallet here: the first turn ends the pass):

    bash
    pm2 logs creddit-ledger-worker --lines 400 --nostream | grep '\[restate\]'
    # [restate] 0x… wsrUSD (0xd3fd…3094): 46 reading(s) restated EXCLUDED -> USD, 2026-08-25 00:00Z -> 2026-09-28 18:00Z
    # [restate] 0x…: a whole-window job of this wallet is already open; it derives the restated history
    #   (this release: #1000's rederive of the wallet; shipped alone: rederive job #N queued over [<floor>,<tip>] (its readings were restated))
    # [restate] wsrUSD (0xd3fd…3094): 46 reading(s) of 1 wallet(s) restated EXCLUDED -> USD, 2026-08-25 00:00Z -> 2026-09-28 18:00Z
    # [restate] done: 1 asset(s) widened, 1 wallet(s) visited, 46 reading(s) restated, 0 held back, …
    sudo -u postgres psql -d creddit -c "SELECT book, rate_source, count(*) FROM onchain_credit.portfolio_position_snapshots WHERE chain_id = 1 AND wallet = '0xe51d05913b0951cf8b48596274bd086efdcc3ed9' AND accounting_asset = '0xd3fd63209fa2d55b07a0f6db36c2f43900be3094' GROUP BY 1, 2"
    # USD only (chain, or series where the getter did not answer); no EXCLUDED
    sudo -u postgres psql -d creddit -c "SELECT id, kind, state, left(error, 120) FROM onchain_credit.portfolio_derive_jobs WHERE chain_id = 1 AND wallet = '0xe51d05913b0951cf8b48596274bd086efdcc3ed9' AND kind IN ('rederive', 'audit') ORDER BY id DESC LIMIT 4"
    # the rederive done (this release: the one #1000's step 5 queued), and the re-audit it queued after it
  4. The next reconciler run (30 1,7,13,19): 0xe51d…'s line reads book-overlays=0 book-withheld=0, and factless=0/0/0 as before (a restated reading is computed from the fact the restatement wrote; one that could not be was held back, never left served stored). Its readings' differ= rises by up to the 46 restated (their stored money columns are the old book's), which the line reports and never pages. The value-parity census (scripts/ops/value-parity.ts --db-url) classes the same 46 readings' stored lines as differing (stored-null, residue): their frozen money columns, which no served path reads for a computed row and step 2 of #981 drops. That is expected, and is not a served-stored row. A wallet that only moved wsrUSD (no reading of it) is not re-derived by the restatement; list any, and re-derive each by hand (the ledger worker):

    bash
    sudo -u postgres psql -At -d creddit -c "SELECT DISTINCT f.wallet FROM onchain_credit.portfolio_flow_events_v2 f WHERE f.chain_id = 1 AND f.asset = '0xd3fd63209fa2d55b07a0f6db36c2f43900be3094' AND NOT EXISTS (SELECT 1 FROM onchain_credit.portfolio_position_snapshots s WHERE s.chain_id = 1 AND s.wallet = f.wallet AND s.accounting_asset = f.asset)"
    # nothing expected (0xe51d… holds readings of it); a wallet printed shows on the line's factless=
  5. The page: Fred opens 0xe51d…'s USD view: the total-return line runs from 2026-08-25 (it was blank until 2026-09-29), and the wsrUSD/AUSD borrowing, dust as a whole, is absent: neither leg in the positions rows or under Not covered, and the USD headline keeps what it booked. (A Fluid smart side and its USDC borrowing on the same wallet are #1000's step 8.)

  6. Record executed: with the release PR, the merge commit, step 2's plan lines and step 3's log lines.

Rollback. Revert the release's merge commit on main (the previous entry's rule for a revert). Nothing is undone in the data, and nothing needs to be: a restated reading is the row a writer covering the asset writes, in the book today's registry gives it, so the previous release values it in that book with no overlay; the rederive it queued derived the wallet under the same registry the previous release reads. Migration 124 stays (an index; the previous release names none). The previous release's dust floor judges legs one by one again.

Staging, before the release ​

Staging runs no worker: a bounded hand-run from the staging checkout restates at its first turn, continues the pass on its idle queue while it has wallets left, and drains the re-derivations it queued before it exits. Rehearse it after a staging deploy, never between a nightly reseed and the next deploy: until 125 reaches prod the reseed drops the composition column, which the worker's loader reads (#1000's staging note). The nightly reseed carries prod's readings but its scrub clears the accounts graph, so a widening is made on purpose, on a staging wallet that holds a covered rate-source asset: its readings put back to what a writer stored before the asset was covered. One at a time, PG_POOL_MAX=4, nothing here names pm2 or touches creddit.

  1. The deploy applies 124 by itself (additive): SELECT count(*) FROM onchain_credit.schema_migrations WHERE filename = '124-snapshot-asset-book-index.sql' on creddit_staging prints 1.

  2. Pick the wallet and the asset: an enrolled staging wallet with readings of an asset the registry books and rates (rate_source not null), and remember them as $W and $A:

    bash
    cd /opt/onchain-credit-staging && set -a && . ./.env.local && set +a
    psql "$DATABASE_URL" -c "SELECT wallet, accounting_asset, book, count(*) FROM onchain_credit.portfolio_position_snapshots WHERE chain_id = 1 AND rate_source IS NOT NULL GROUP BY 1, 2, 3 ORDER BY 4 DESC LIMIT 5"
    : "${W:?}" "${A:?}"
    psql "$DATABASE_URL" -c "CREATE TABLE IF NOT EXISTS public.restate_check AS SELECT wallet, venue, position_key, snapshot_ts, book, rate_raw, rate_source FROM onchain_credit.portfolio_position_snapshots WHERE chain_id = 1 AND wallet = '$W' AND accounting_asset = '$A'"
    psql "$DATABASE_URL" -c "UPDATE onchain_credit.portfolio_position_snapshots SET book = 'EXCLUDED', rate_raw = NULL, rate_source = NULL WHERE chain_id = 1 AND wallet = '$W' AND accounting_asset = '$A'"
  3. The plan: npx tsx scripts/ops/restate-covered-readings.ts --plan names $W and $A with the count step 2 updated, would restate EXCLUDED -> <its book>, and nothing written.

  4. The worker, by hand: PG_POOL_MAX=4 LEDGER_WORKER_EXIT_WHEN_IDLE=1 bash scripts/worker/run-worker.sh. Its first lines are the [restate] lines (the readings restated, a rederive of $W queued); it then drains that job and the re-audit after it, and exits. Then every reading is back as it was:

    bash
    psql "$DATABASE_URL" -c "SELECT count(*) FILTER (WHERE s.book IS DISTINCT FROM c.book) AS book_differs, count(*) FILTER (WHERE s.rate_source IS NULL) AS no_fact FROM onchain_credit.portfolio_position_snapshots s JOIN public.restate_check c USING (wallet, venue, position_key, snapshot_ts) WHERE s.chain_id = 1"
    # 0 | 0: every reading back in its book, each with a rate fact. Its source can differ from the one
    # stored: a `live` fact the 6h tick kept becomes the chain's (or the series') answer at the block,
    # which is what the registration replay writes for a past block.
    psql "$DATABASE_URL" -c "DROP TABLE public.restate_check"
  5. A second hand-run restates nothing ([restate] nothing to restate …), and the plan says the same.

Repo lending: two market types, ETH/PYUSD/RLUSD, isolated markets by approval (migration 127): prod steps, in order ​

  • belongs to: the repo-lending release (two market types, the ETH, PYUSD and RLUSD tabs, the manual isolated-market rule; branch feat/repo-lending-eth-pyusd-rlusd-isolated-rule), migration 127
  • executed: 2026-10-02

v0.75.0 (release PR #1005, merge 1bb76faf, deployed 20:04Z; integration fix #1006). Step 2: 127 by the runner after the deploy; repo_listed 7; Morpho exposure rows 11600 attributed of 14000. Step 3: 6 shown qualifying, 1 shown failing (AA_FalconXUSDC -> USDC, $6.5M under the $10M floor: proposed removal, left for the owner), 29 proposed additions = the owner's 29. Step 4: approve: 29 approved, 0 already on the page, 0 refused, 0 failed. Steps 5–7: backfill-morpho exit 0; backfill-repo-reserves 5796 ok, 0 failed (PYUSD from 2025-08-12, RLUSD from 2026-09-01); refresh-collateral-exposure and refresh-lending-positions exit 0. Step 8: deploy re-run 21:10Z.

What it changes for a user, in one line: the Type column reads Pooled or Isolated (Fluid is Pooled), there are PYUSD, RLUSD and ETH tabs (ETH in ether, measured against Lido staking), and which isolated markets the page lists is the owner's approval, market by market; the deploy itself lists and delists nothing.

The invariants this order protects. Deploying changes no visible listing: until migration 127 lands, every reader serves the pre-127 set through its schema probe, and the migration backfills repo_listed to exactly that set. Nothing lists or delists an isolated market except repo-isolated-check.ts --approve / --remove. /carries is unchanged: sync-carries.ts keeps its carry classification and never touches the repo approval.

Every prod step below needs the owner's go, step by step; merging the release is his go for step 1 only.

  1. Deploy (the release merge). Nothing moves on the page. Do NOT run sync-carries.ts until step 2 is done: it no longer writes a repo track, so a run before the migration would empty the set the backfill reads (a persisting run refuses until the column exists; --dry-run is fine).

  2. Apply migration 127 (owner's go), right after the deploy:

    bash
    cd /opt/onchain-credit && scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)"
    sudo -u postgres psql -d creddit -c "SELECT count(*) AS listed FROM onchain_credit.morpho_market_registry WHERE repo_listed"
    # must equal the isolated markets on the page before the deploy (7 on 2026-10-01)
    sudo -u postgres psql -d creddit -c "SELECT count(*) FILTER (WHERE market_id <> '') AS attributed, count(*) AS morpho_rows FROM onchain_credit.market_collateral_exposure WHERE protocol = 'Morpho'"

    The page then reads repo_listed, which is the same set, so it still shows the same markets.

  3. The repo check, report only (no write; owner's go to run it on prod):

    bash
    scripts/run-cron.sh repo-isolated-check.ts
    # run-cron.sh writes the report to the job's log, not the terminal; keep this run's slice:
    awk '/^--- .* ---$/{s=""} {s=s $0 ORS} END{printf "%s", s}' \
      /tmp/onchain-credit-cron/onchain-credit-repo-isolated-check.log > /tmp/repo-check-$(date -u +%F).txt

    Hand the owner the PROPOSED ADDITIONS and any SHOWN BUT FAILING lines. Expected: the seven shown markets qualifying (all seven passed the new rule on 2026-10-01), and the census's 28 new ones as proposed additions. A WARNING: no current stored price for PYUSD (or RLUSD) line means that token's price bars are behind and its markets cannot qualify yet: fix the price feed and re-run before step 4, or its markets would be refused there. A rehearsal of this report against the fixture database on 2026-10-02 (10 approved houses there, not prod's 21; current PYUSD and RLUSD bars inserted by hand) proposed 29, among them PYUSD 7, RLUSD 5 and ETH 3, through V1 and Vaults V2 suppliers alike.

  4. Approve what the owner approved (owner's go). On 2026-10-02 the owner approved 29 markets: the 28 that the 2026-10-01 census found qualifying and not shown (35 qualifying, 7 shown; by asset USDC 16, USDT 5, ETH 3, PYUSD 7, RLUSD 4, USDS and GHO none), plus WBTC to RLUSD, which qualified on 2026-10-02 and which he approved the same day. Approve every market below that still qualifies, in one run. A market below that no longer qualifies is refused and stays off. A market that qualifies but is NOT below goes back to the owner instead.

    #LoanCollateralMarket id
    1USDCPST0x002278ea242ec722813b4fe3c8eeaa07dbc331c731cc0b4248a1bf0771f933ea
    2USDCmF-ONE0xef2c308b5abecf5c8750a1aa82b47c558005feb7a03f4f8e1ad682d71ac8d0ba
    3USDCwFalconX0x2a0b893471c785a1f0fda00df7fca578b703eef7ae7186d2429c2824b5212467
    4USDCweETH0x85252bb8485c99bba46fe149c7dd2aad83672640f53c630890673cf1848ba16e
    5USDCUSD30xe3df58f9d3011b7481ff36b939fa5f8da642f34ea5792d25d3958dbf1efa26d7
    6USDCfxSAVE0x17f7ae1b52670010976b3fe41324cbb2b1eb7dd8f492e51764b2828371b86b84
    7USDCdCOMP0x24852d8d7464402ddcd717415e009d42bf7427d6a8893487f83c75ee0f4a0ea6
    8USDCstrUSD0x975c6e8b71073a82216ae464bc44f67d71988450d2542d635d88bc78fca344b1
    9USDCapyUSD0x9c28c8fa039a8df548a7f27adf062d751b0f2e9b9131931810535543adb23291
    10USDCwstETH0x7e585a933ffe8443c371b4f8cfeb4430f5f6a14c2f32a898c26662c67a1cb8b8
    11USDCsteakEURCV0xc498f4bfdda99e60ea8eb04c1e145654a70bc59da76ef9c6ed54a1314d78e5b5
    12USDCwsrUSD0x1590cb22d797e226df92ebc6e0153427e207299916e7e4e53461389ad68272fb
    13USDTsUSDS0x26b178d49895f80ca3c39b2745efc4cd9adcddfcc73dae93e531e86977ec4d96
    14USDTcbBTC0x4fe72543c5c95cd6b5f3cb516cd235ba882e2e705fe3424db6f99dfe5811d0d3
    15ETH (WETH)wstETH0xb8fc70e82bc5bb53e773626fcc6a23f7eefa036918d7ef216ecfb1950a94a85e
    16ETH (WETH)wstETH0xd0e50cdac92fe2172043f5e0c36532c6369d24947e40968f34a5e8819ca9ec5d
    17ETH (WETH)weETH0x37e7484d642d90f14451f1910ba4b7b8e4c3ccdd0ec28f8b2bdb35479e472ba7
    18PYUSDPRIME0x41c41d0c9aadbf4751f5ee215ed5a16954a4b34e1b70fca5393d4b08858fa3fa
    19PYUSDkBTC0xe51f9aaad25d0e755429cf77076b3c2d37cb1228ed81f8a5482f2102c220eef5
    20PYUSDsUSDe0x90ef0c5a0dc7c4de4ad4585002d44e9d411d212d2f6258e94948beecf8b4c0d5
    21PYUSDweETH0x85d59152eeeab7ca024804895b358868d8dd1e134171be400d7792d5604a212c
    22PYUSDsyrupUSDC0xc9629945524f3fde56c7e8854a6c3d48e76b9d97236abbe73c750fcc7aeb8501
    23PYUSDPST0xb4977179610abfecfc8b76255a002c16b33f46d077beb86e5911e1fe9ee6e512
    24PYUSDmWIN0xeecbfa4b6caa83c5000ce68a77808c80504e2ff56e81095c7742a615ecd9c774
    25RLUSDkBTC0x15bb2a6af0c909eed19fb1f2ceeead34ecbdcba626de752c6b09389ee14eec32
    26RLUSDweETH0xea4bfb18df0ee6bffb7b3f0270899a8adb92ab6b684709634c8276128813cfd4
    27RLUSDUSDe0xd9d2fc090bdbab1804ea960dd6669b62357787e5816f575f14ca4e6d999614bf
    28RLUSDcbBTC0xffd010618ed3cb39bb2c5de0e3e58d3d2ec9f52187a180f29723c31756a939bc
    29RLUSDWBTC0xa128dddc761075df9a9a60689f3a41a989b245aad506352c509c0c3a76a9ec6b
    bash
    scripts/run-cron.sh repo-isolated-check.ts --approve \
      0x002278ea242ec722813b4fe3c8eeaa07dbc331c731cc0b4248a1bf0771f933ea \
      0xef2c308b5abecf5c8750a1aa82b47c558005feb7a03f4f8e1ad682d71ac8d0ba \
      0x2a0b893471c785a1f0fda00df7fca578b703eef7ae7186d2429c2824b5212467 \
      0x85252bb8485c99bba46fe149c7dd2aad83672640f53c630890673cf1848ba16e \
      0xe3df58f9d3011b7481ff36b939fa5f8da642f34ea5792d25d3958dbf1efa26d7 \
      0x17f7ae1b52670010976b3fe41324cbb2b1eb7dd8f492e51764b2828371b86b84 \
      0x24852d8d7464402ddcd717415e009d42bf7427d6a8893487f83c75ee0f4a0ea6 \
      0x975c6e8b71073a82216ae464bc44f67d71988450d2542d635d88bc78fca344b1 \
      0x9c28c8fa039a8df548a7f27adf062d751b0f2e9b9131931810535543adb23291 \
      0x7e585a933ffe8443c371b4f8cfeb4430f5f6a14c2f32a898c26662c67a1cb8b8 \
      0xc498f4bfdda99e60ea8eb04c1e145654a70bc59da76ef9c6ed54a1314d78e5b5 \
      0x1590cb22d797e226df92ebc6e0153427e207299916e7e4e53461389ad68272fb \
      0x26b178d49895f80ca3c39b2745efc4cd9adcddfcc73dae93e531e86977ec4d96 \
      0x4fe72543c5c95cd6b5f3cb516cd235ba882e2e705fe3424db6f99dfe5811d0d3 \
      0xb8fc70e82bc5bb53e773626fcc6a23f7eefa036918d7ef216ecfb1950a94a85e \
      0xd0e50cdac92fe2172043f5e0c36532c6369d24947e40968f34a5e8819ca9ec5d \
      0x37e7484d642d90f14451f1910ba4b7b8e4c3ccdd0ec28f8b2bdb35479e472ba7 \
      0x41c41d0c9aadbf4751f5ee215ed5a16954a4b34e1b70fca5393d4b08858fa3fa \
      0xe51f9aaad25d0e755429cf77076b3c2d37cb1228ed81f8a5482f2102c220eef5 \
      0x90ef0c5a0dc7c4de4ad4585002d44e9d411d212d2f6258e94948beecf8b4c0d5 \
      0x85d59152eeeab7ca024804895b358868d8dd1e134171be400d7792d5604a212c \
      0xc9629945524f3fde56c7e8854a6c3d48e76b9d97236abbe73c750fcc7aeb8501 \
      0xb4977179610abfecfc8b76255a002c16b33f46d077beb86e5911e1fe9ee6e512 \
      0xeecbfa4b6caa83c5000ce68a77808c80504e2ff56e81095c7742a615ecd9c774 \
      0x15bb2a6af0c909eed19fb1f2ceeead34ecbdcba626de752c6b09389ee14eec32 \
      0xea4bfb18df0ee6bffb7b3f0270899a8adb92ab6b684709634c8276128813cfd4 \
      0xd9d2fc090bdbab1804ea960dd6669b62357787e5816f575f14ca4e6d999614bf \
      0xffd010618ed3cb39bb2c5de0e3e58d3d2ec9f52187a180f29723c31756a939bc \
      0xa128dddc761075df9a9a60689f3a41a989b245aad506352c509c0c3a76a9ec6b \
      --note "owner approval 2026-10-02 (census 2026-10-01 + WBTC to RLUSD)" --by <operator>

    Each is judged again; a refused market prints its reasons, the rest go ahead, and the run ends with one approve: N approved, N already on the page, N refused, N failed line (read it back with the same awk as step 3). A refusal exits 0; only a failed write exits non-zero (and pages, as every run-cron.sh job does). An approved market is listed once its first snapshot lands (step 5, or the next 6h tick), never as a row of dashes.

  5. Rate history for the approved markets (owner's go; archive-RPC heavy, resumable with --since), the command --approve printed: every 6h window from the 2025-05-21 floor, rates only, and a window before a market existed is skipped, not written:

    bash
    scripts/run-cron.sh backfill-morpho.ts --market <id>,<id>,...

    Their collateral panels arrive with the next 6h refresh-assets.ts tick.

  6. PYUSD and RLUSD rate history (owner's go; archive-RPC heavy, a few hours, resumable with --from):

    bash
    scripts/run-cron.sh backfill-repo-reserves.ts --assets PYUSD,RLUSD

    The PYUSD and RLUSD rows appear with their first snapshot (the first 6h tick after the deploy, or this walk, whichever lands first; a market is never listed before it has one), and until the walk finishes they chart only from that tick. ETH needs no walk (WETH and Fluid's native ether have history since 2025-05-21).

  7. Collateral breakdowns for the new debt assets (owner's go). The 6h crons do this by themselves; running them by hand fills the panels now:

    bash
    scripts/run-cron.sh refresh-collateral-exposure.ts   # Fluid ETH
    scripts/run-cron.sh refresh-lending-positions.ts     # Aave/Spark PYUSD, RLUSD, ETH

    The first lending-positions run scans each new debt token's history from the venue's deployment; WETH's is the largest, so expect a long run (chunked; a second run only scans from its cursor).

  8. Re-run the deploy (or wait for the 30-minute regeneration) so the page prerenders with the new rows, and check the tabs on the live page.

  9. Record executed: with the date, step 2's counts, step 3's group counts and step 4's approved and refused keys.

Staging. The staging deploy applies 127 after its build (the build itself renders the pre-127 set), and the nightly reseed reverts it until prod has it; staging runs no refreshers. The report in step 3 can be rehearsed there against creddit_staging with no owner's go (it writes nothing); an approval there is rolled back by the next reseed.

Rollback. A code rollback does not roll back the database, and the old code ignores both new columns. But the old page reads the repo TRACK, which this release's sync-carries.ts no longer writes: after any post-release sync, the rolled-back page shows no isolated markets until the old sync-carries.ts has run once (it recomputes the track under the old rule).

f(x) Protocol: fxSAVE, fxUSD and the pool share fxSP (migration 126): prod steps, in order ​

  • belongs to: f(x) Protocol's fxSAVE profile, fxUSD and the stability-pool share (branch feat/fx-protocol-fxsave), migration 126
  • executed: 2026-10-02

v0.75.0 (release PR #1005, merge 1bb76faf, deployed 20:04Z; integration fix #1006). Step 2: 126 by the runner right after the deploy (APPLY line seen), three rows exactly as expected. Step 3: backfill-fxsave 2194 ok / 0 fail (1.000127 → 1.121626), backfill-fxsp 2553 ok / 0 fail (0.999984 → 1.010230), token-supply and apy-30d exit 0. Step 4: hand refresh-assets 20:26Z: fxUSD bars 2026-01-01 → 2026-10-02 18:00 (6595); fxSAVE profile row (productive $82.6M, APY 6.82%). Step 5: no bare fxSAVE/fxUSD/fxSP readings; 0xe51d… holds PT-fxSAVE (62 readings held, as described); its rederive ran after the fxUSD bars existed.

What it changes for a user, in one line: fxSAVE gets an asset profile, and a wallet holding fxSAVE, fxUSD, the stability-pool share fxSP or the Pendle PT on fxSAVE sees it valued in the USD view: fxSAVE and fxSP at their redemption rates times fxUSD's market price, under Variable rate assets (fxSAVE with a link to the profile), fxUSD as an Idle asset, and PT-fxSAVE-29OCT2026 in the USD book instead of under Other. Expand only: three new registry rows, one CHECK widened; nothing changed or deleted.

  1. The deploy (merge staging into main). What answers from the compiled seed from the first process start: the feed set, the rate getters, the capacity pass and the book fallback (so a PT leg on the pool share books USD at once). What does NOT: the bare-wallet sweep and the derivation's wallet-token universe read the database's rows (loadPortfolioTokens, behind a 60-second cache), so neither sees fxSAVE, fxUSD or fxSP until step 2 has run. A reading taken in between (the six-hourly portfolio tick, a page-load sync, a registration replay) stores no wallet leg for them, and nothing re-reads a tick's reading later.

  2. Migration 126, at once after the deploy, before the next six-hourly portfolio tick (refresh-portfolio.ts at 50 */6 UTC: 00:50, 06:50, 12:50 or 18:50), by the standing runner (it carries no destructive tag, so migrate.sh applies it with whatever else the release has pending). In a release that also carries migration 127 (its step 2 runs this same runner right after the deploy), that run applies 126 too, and this step is the check below alone:

    bash
    cd /opt/onchain-credit && scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)"
    sudo -u postgres psql -d creddit -At -c "SELECT symbol, status, wallet_tracked, book, class, valuation, feed, underlying_address, rate_kind, rate_getter, liquidity, mint_terms, redeem_terms, capacity_reader, profile_ticker, issuer FROM onchain_credit.portfolio_tokens WHERE chain_id = 1 AND address IN ('0x7743e50f534a7f9f1791dde7dcd89f7783eefc39', '0x085780639cc2cacd35e474e71f4d000e2405d8f6', '0x65c9a641afceb9c0e6034e558a319488fa0fa3be') ORDER BY 1"

    Expect exactly (read off a fixture built from this migration):

    text
    fxSAVE|active|t|USD|variable_rate|composed||0x085780639cc2cacd35e474e71f4d000e2405d8f6|getter|{"kind": "fx_savings_basket"}|primary_buffer|instant|instant|fx_savings|fxSAVE|f(x) Protocol
    fxSP|active|t|USD|variable_rate|composed||0x085780639cc2cacd35e474e71f4d000e2405d8f6|getter|{"kind": "fx_pool_basket"}|primary_buffer|instant|instant|fx_savings||f(x) Protocol
    fxUSD|active|t|USD|par|market|dune_tape||||secondary|||||f(x) Protocol

    The rows match the compiled seed, so no restart is needed: the processes that loaded the registry at start already answer these rows from the seed, and the sweep picks them up within a minute.

  3. fxSAVE's and the pool share's rate histories, each from its first deposit, before the first tick reads them (fxSAVE's profile 30-day APY and returns are computed from its series, and each series is its getter's fallback). A prod write to market data, by the standing backfill tooling:

    bash
    /opt/onchain-credit/scripts/run-cron.sh backfill-fxsave.ts        # ~2,200 windows, 3 archive reads each
    /opt/onchain-credit/scripts/run-cron.sh backfill-fxsp.ts          # ~2,550 windows, 2 archive reads each
    /opt/onchain-credit/scripts/run-cron.sh backfill-token-supply.ts  # fills NULL total_supply, every token
    /opt/onchain-credit/scripts/run-cron.sh backfill-apy-30d.ts       # recomputes apy_30d, every token (pure DB)

    fxSAVE's opens at 2025-04-02 12:00 UTC and the pool share's at 2025-01-02 18:00 UTC (why). A non-zero exit after a long run is usually one transient RPC failure: a failed window is skipped, never zero-written, and the upsert makes a re-run fill only the gaps. The other two are the shared, idempotent follow-ups every share-rate backfill closes with. Check:

    sql
    -- read-only
    SELECT token_symbol, min(snapshot_ts), max(snapshot_ts), count(*), count(apy_30d), count(total_supply)
      FROM onchain_credit.token_yield_apy
     WHERE token_address IN ('0x7743e50f534a7f9f1791dde7dcd89f7783eefc39', '0x65c9a641afceb9c0e6034e558a319488fa0fa3be')
     GROUP BY 1 ORDER BY 1;

    fxSAVE's min is 2025-04-02 12:00 and fxSP's 2025-01-02 18:00, each about four rows a day since, and the newest share_rate near 1.12 for fxSAVE (1.1215 at block 26,103,249 on 2026-10-02) and near 1.01 for fxSP (1.0102 at block 26,103,423).

  4. The first six-hourly refresh-assets tick, by hand once the deploy has finished (never during it: the build prerenders from the database): scripts/run-cron.sh refresh-assets.ts. It buys fxUSD's price history (the mirror's auto-backfill on add: 2026-01-01 -> now in three 90-day Dune executions, roughly a dozen credits once, bounded by DUNE_MAX_CREDITS_PER_RUN), writes fxSAVE's newest series row and its profile row, and reads its route. Then check, rather than reading counts off the log:

    • fxUSD's series: SELECT min(bar_ts), max(bar_ts), count(*) FROM onchain_credit.token_price_bars WHERE chain_id = 1 AND token_address = '0x085780639cc2cacd35e474e71f4d000e2405d8f6' reaches back to 2026-01-01 and forward to within a few hours;
    • the profile row: SELECT ticker, name, issuer, productive_usd, underlying_usd, current_apy, updated_at FROM onchain_credit.assets WHERE ticker = 'fxSAVE' returns one fresh row (a failure prints [yield-token-assets/fail] fxSAVE). Its two dollar columns are converted at fxUSD's stored bar, so they are null on a tick that ran before that bar existed and fill on the next;
    • the capacity pass read fxSAVE and fxSP through the fx_savings reader: an uncapped mint leg each, and a redeem leg of the vault's whole stake for fxSAVE (about 82.5M fxUSD-equivalents on 2026-10-01) and of the whole pool for fxSP (about 84.7M on 2026-10-02), no refusal. cap-appeared (fxSAVE's maxDeposit answered a real cap) or asset-mismatch (the vault or the pool was re-pointed) is a finding for Fred, not a flake; a zero mint leg means USDC is below the pool's depeg price and every deposit is refused, which is a fact.
  5. GATED: re-derive the enrolled wallets that ever touched fxSAVE, fxUSD, fxSP or the PT on fxSAVE, and only those, AFTER step 4 (a re-derivation before fxUSD's bars exist would store those rows with no market value). A prod write: take it with explicit approval. Their transfers are already ingested (the wallet-token stream reads every ERC-20 Transfer touching an enrolled wallet, registered token or not), but every ledger row for them was derived while neither token had a row, so it carries that answer until the wallet is derived again. Scope it read-only first, one EXISTS per branch so each uses its own index:

    sql
    -- read-only: the wallet list for the insert below
    WITH w AS (SELECT uid, '0x000000000000000000000000' || substr(uid, 3) AS t FROM onchain_credit.accounts),
         m AS (SELECT market_id FROM onchain_credit.morpho_market_registry
                WHERE chain_id = 1
                  AND (collateral_address = '0x7743e50f534a7f9f1791dde7dcd89f7783eefc39'
                       OR collateral_address = '0x079c3469143804af5d0d645a878c371dbe8d038e'))
    SELECT w.uid
      FROM w
     WHERE EXISTS (SELECT 1 FROM onchain_credit.raw_events e
                    WHERE e.chain_id = 1
                      AND e.address IN ('0x7743e50f534a7f9f1791dde7dcd89f7783eefc39', '0x085780639cc2cacd35e474e71f4d000e2405d8f6',
                                        '0x65c9a641afceb9c0e6034e558a319488fa0fa3be', '0x079c3469143804af5d0d645a878c371dbe8d038e')
                      AND e.topic0 = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
                      AND (e.topic1 = w.t OR e.topic2 = w.t))
        OR EXISTS (SELECT 1 FROM onchain_credit.raw_events e
                    WHERE e.chain_id = 1 AND e.stream = 'morpho'
                      AND e.topic1 IN (SELECT market_id FROM m)
                      AND (e.topic2 = w.t OR e.topic3 = w.t))
     ORDER BY 1;

    Zero rows means nothing to do. Otherwise queue one rederive per wallet with the insert the native-ether release uses (its step 7), restricted to that list (AND a.uid = ANY ('{<the list>}'::text[])), and read it done from portfolio_derive_jobs. A wallet holding the Pendle PT on fxSAVE (0x079c…038e, the Transfer branch above) is in scope for it: the PT settles in the pool share, which this migration books, so its ledger rows change too. So is one that posted the PT as Morpho collateral without ever holding it (a bundler can buy and post it in one transaction): that is the second collateral in m.

    And the stored readings, the wsrUSD lesson. A re-derivation rebuilds the ledger; it does not re-book a reading, and a reading is served in the book it was written in. The bare-wallet sweep never read fxSAVE, fxUSD or fxSP before 126 (none was tracked), so the readings that can exist are of fxSAVE posted somewhere a venue reader already read it, and of the PT on fxSAVE: the Pendle reader reads every listed market's PT, so a bare holding of it was stored with the pool share as its accounting asset, booked EXCLUDED (a PT on an untracked payout asset), and a PT posted as Morpho collateral under the PT's own address. Check, read-only:

    sql
    SELECT wallet, accounting_asset, book, count(*), min(snapshot_ts), max(snapshot_ts)
      FROM onchain_credit.portfolio_position_snapshots
     WHERE chain_id = 1 AND accounting_asset IN ('0x7743e50f534a7f9f1791dde7dcd89f7783eefc39', '0x085780639cc2cacd35e474e71f4d000e2405d8f6',
                                                '0x65c9a641afceb9c0e6034e558a319488fa0fa3be', '0x079c3469143804af5d0d645a878c371dbe8d038e')
     GROUP BY 1, 2, 3 ORDER BY 1, 2, 3;

    No row (or none outside USD) means nothing to restate. The rest is the worker's coverage restatement's (its entry, already on staging, so it ships with this release or before it), at its first pass after step 2 has written the three rows, and it splits them in two; its read-only plan (restate-covered-readings.ts --plan) names both first:

    • fxSAVE read as Morpho collateral before it was covered (the 0xe51d… shape), and any fxSP reading the same way, are re-booked into USD, and the pass queues the wallet's rederive itself; never by hand. That re-derivation needs fxUSD's bars: when the check finds such a row, run step 4 before the worker's first pass after step 2 (in a release that stops the worker across the deploy, before it is started again). Run before the bars exist, the movements it derives carry no market value, and the wallet has to be re-derived once more after step 4.
    • Every PT-fxSAVE reading from before the release is HELD, bare or posted as collateral, with the reason its value in USD reads a rate beside its own (0x65c9…a3be), which this step does not write: the pass restates a reading's one rate column only (the PT's own), and its value in dollars also reads the pool share's, which the pass does not write (rate_facts, migration 128). So a PT-fxSAVE holder's history before the release stays unpriced (EXCLUDED, blank in the USD view), while its re-derived ledger holds the PT in USD from its first purchase, so its reconciler line keeps book-overlays above zero. That is the expected state, not a failed pass; re-pricing that history (the restatement writing the payout asset's rate into the reading's rate_facts) is a follow-up for Fred, not this release. Update, release v0.87.0: that follow-up shipped with the fix to the v0.87.0 review's B2 (the restatement now states every rate a reading's value reads), so it restates any such reading still stored and re-derives its wallet; none are on prod as of 2026-10-12 (no PT-fxSAVE reading or flow exists there; 143's entry).

    And the PT's new readings compute (migration 128, its entry). A PT-fxSAVE reading written after the deploy carries the pool share's rate in its rate_facts beside the PT's own, so the read path computes it from its own facts. That closes, for it, the class #981 step 2's column drop waited on, "a PT leg over a composed payout asset" (the contract list). Shipped without 128, such a reading would carry no fact for the pool share's rate and be served from its stored value_market unless another leg of the same reading kept that rate (a bare fxSP balance beside it), counted on value-parity.ts's served stored (no rate fact) line.

    And the stretch no reading read. A wallet that held fxSAVE, fxUSD or fxSP in its bare wallet before this release has no reading of it from before the release (the sweep did not read an unregistered token), while its re-derived ledger holds the leg from its first transfer. (The PT's gap is the other one, above: its readings exist and stay held.) The reading top-up (its entry, scripts/ops/topup-unread-readings.ts --wallets <the list>, plan first, a prod write on the owner's go) fills the readings that wallet's registration replay wrote. It does not re-read the readings the six-hourly tick wrote between the wallet's registration and this release (it treats a leg missing from a tick reading as a failed read and keeps the record), so over that stretch the history withholds the holding (W1 unread-endpoint) and the reading audit reports the leg unread. An empty scope list above means none of this applies; any wallet on it with a bare-wallet holding is a finding for Fred.

  6. Show the profile at once (optional): /asset-profiles is ISR (revalidate = 3600), so the row appears within the hour on its own; re-running the deploy re-prerenders the page against the row now (the ISR trap).

Nested rate facts on readings (migration 128): first deploy ​

  • belongs to: issue #981 (the contract release's step-2 precondition: a reading keeps every rate its value read; branch feat/nested-rate-facts), migration 128
  • executed: 2026-10-02

v0.75.0 (release PR #1005, merge 1bb76faf, deployed 20:04Z; integration fix #1006). 128 alone by hand 13:59Z, before the deploy; recorded, rate_facts jsonb + portfolio_pos_rate_facts_chk present. Census after the release: served stored (no rate fact) 0 on every line kind.

What it changes for a user, in one line: nothing a user sees moves; a holding whose value reads a second rate (a wrapper over a chain-rated fund such as wFalconX, a fixed-rate principal token whose payout asset itself earns a rate) is valued at read from the rates read at its own moment, like every other holding, instead of from the figure frozen when it was written, which is what lets the next contract step drop those frozen figures.

What it does, and what it leaves.

  • From the deploy, every reading writer keeps every rate the reading's value read, in rate_facts (the observed rate facts): the 6h checkpoint and its recompose path, the page load's stored reading, the registration replay and the reading top-up through it, the smart-side restatement, and the reading audit's copies (meta.audit.reading). Every read that values a reading (the page, the reconciler, the census, the activity statement, the PT exit cost) answers its needs from them first, then from its reading's pooled one-column facts, then serves it stored (the loader rule).
  • Migration 128, expand only: a nullable rate_facts jsonb on portfolio_position_snapshots with the CHECK portfolio_pos_rate_facts_chk (an object) (database). No row is written by it.
  • No backfill. Readings written before the deploy keep rate_facts NULL and are valued exactly as before: computed from their reading's pooled facts, or served stored and counted (factless=) where those cannot answer. The owner deletes every current wallet and its records (Fred, 2026-10-02), so a wallet connected after the deploy is built with every rate stated from its first reading. The rate-facts backfill (scripts/ops/backfill-rate-facts.ts) fills what it filled before (a pre-116 row's one column) and skips a row that carries its own map.
  • What stays held: the coverage restatement still writes a widened reading's one column only, so a leg whose value reads a rate beside its own stays held back there (left as written, on its asset's line). No asset of that shape is waiting to be widened. (Lifted in release v0.87.0: 143 made apyUSD such an asset, and the restatement now writes every rate a widened reading's value reads into its rate_facts; 143's entry.)

Prod, in order. Step 1 writes prod and needs the owner's go; step 2 is the release merge.

  1. Migration 128 ALONE, BY HAND, BEFORE the deploy, from the staging checkout at the release PR's head (the 124 / 125 pattern). Before, because the new writers insert into rate_facts and the new readers (the loader, the reconciler, the activity statement, the PT exit cost, the census) select it from their first start: Postgres resolves a column when it parses a statement, so a deploy that lands first fails every reading write and every portfolio page load until the column exists. Safe before, because it is expand only: the running release never names the column, and a code rollback keeps working with it in place. Its place in the release's sequence, and never the runner: in a release that also carries #997, #998, #1000 and #989, 128 joins the "before the deploy, by hand" group of their order, after #997's 123, #989's 124 and #1000's 125 (it is independent of all three). 126 (f(x), its step 2) and 127 (repo lending, its step 2) come AFTER the deploy, by the standing runner, 126 before the next six-hourly portfolio tick: so 128, though numbered after both, is applied BEFORE both, it is independent of each, and the runner that applies them right after the deploy finds 128 already recorded and skips it. So do NOT run scripts/ops/migrate.sh for 128: before the deploy it applies every file prod's ledger lacks and would take 123, 124, 125, 126 and 127 out of their entries' order (#997's eUSDe census must precede 123, 124's index build runs between ticks, 126 and 127 belong right after the deploy).

    bash
    git -C /opt/onchain-credit-staging rev-parse HEAD                      # = the release PR's head commit
    git -C /opt/onchain-credit-staging status --porcelain -- scripts/sql   # prints nothing
    f=128-reading-rate-facts
    sudo -u postgres env "PGOPTIONS=-clock_timeout=10s -cstatement_timeout=300s" \
      psql -v ON_ERROR_STOP=1 -X -q -1 -d creddit -f /opt/onchain-credit-staging/scripts/sql/$f.sql \
    && sudo -u postgres psql -q -d creddit -c "INSERT INTO onchain_credit.schema_migrations(filename) \
         VALUES ('$f.sql') ON CONFLICT DO NOTHING"
    sudo -u postgres psql -At -d creddit -c "SELECT count(*) FROM onchain_credit.schema_migrations WHERE filename = '$f.sql'"   # 1

    Check: the count reads 1, and \d onchain_credit.portfolio_position_snapshots lists rate_facts jsonb and the CHECK portfolio_pos_rate_facts_chk. The CHECK reads each monthly partition once to validate (every row is NULL: it fails nothing); a run that aborts on lock_timeout is run again when the table is quiet. Idempotent (a re-run prints one NOTICE).

  2. The deploy (merge staging into main).

  3. The check, read-only, on a wallet connected after the deploy (after the owner's wipe, or a fresh connect): 0xe51d05913b0951cf8b48596274bd086efdcc3ed9, which holds wsrUSD as Morpho collateral, once its registration has built its history. wsrUSD composes onto rUSD in one level, so its own column always answered it: this wallet shows the facts are written and read; a connected wallet holding wFalconX, or a principal token over a composed payout asset, is where the release turns a reading from served stored to computed.

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    W=0xe51d05913b0951cf8b48596274bd086efdcc3ed9
    # the census: every line `served stored (no rate fact) 0`, and `computed-null 0` on the readings
    npx tsx scripts/ops/value-parity.ts --db-url "$DATABASE_URL" --wallets "$W"
    # the reconciler's value line: factless=0/0/0
    npx tsx scripts/ops/reconcile-ledger.ts --wallet "$W" | grep values=
    # a reading written since the deploy that keeps its own rate but no map: expect 0
    psql "$DATABASE_URL" -tAc "SELECT count(*) FROM onchain_credit.portfolio_position_snapshots s
      WHERE s.chain_id = 1 AND s.updated_at > '<the deploy time>' AND s.rate_raw IS NOT NULL AND s.rate_facts IS NULL
        AND s.venue <> 'pendle'
        AND NOT EXISTS (SELECT 1 FROM onchain_credit.pendle_markets m WHERE m.chain_id = 1 AND m.pt_address = s.accounting_asset)"

    Until the wipe, wallets built before the deploy keep reporting what they reported (their rows are not backfilled); the reconciler's population run reaches factless=0/0/0 once every wallet left was built after it.

    Not closed by this release: #981's census residue on 0xe51d…, the seizure of 4.2165 wsrUSD at block 25966539 (stored 4.62 / 4.63, computed null on both lines). It is no rate gap and no principal token: it is a book-withheld movement. The read values a movement in today's registry book (USD since migration 119) and withholds it where its leg's readings state another book, and that leg's 46 readings from 2026-08-25 to 2026-09-28 were written EXCLUDED, before 119 covered wsrUSD. The pending coverage restatement (its entry) or the owner's wipe clears it; a wallet connected from scratch books wsrUSD in USD from its first reading, so its readings and the movement agree and the movement is valued.

  4. Record executed: with the date and step 3's census line, values= line and count.

Staging. The staging deploy applies 128 (migrate.sh, additive) and no owner's go is needed to rehearse step 3 there (read-only). The nightly reseed restores prod's schema without rate_facts until 128 reaches prod, and every reading write and portfolio page load names the column, so from a 03:00 reseed until the next staging deploy every reading write and portfolio page on staging fails: redeploy staging after the reseed (or touch /root/.reseed-paused across a validation window) before reading anything into a failure. The reseed's scrub empties every portfolio table, so staging's wallets are always built under the release it runs.

Rollback. A code rollback does not roll back the database, and the previous release never names rate_facts. Rows this release wrote keep rate_raw / rate_source as before, so the previous release values them exactly as it valued every row (a two-level composition or a principal token over a composed payout is served stored again where no other leg of its reading kept the second rate). Never drop the column on a rollback (expand / contract); a roll-forward finds it filled where this release wrote and NULL where the rolled-back code wrote, which the read answers from the reading's pool as before.

f(x)'s fee-free fxSAVE exit, held in settlement (no migration): prod steps, in order ​

  • belongs to: the escrow class fx-fxsave-cooldown (family fx-locked-proxy; branch feat/fxsave-cooldown-escrow), no migration; it presumes the f(x) release (migration 126: fxSAVE, fxUSD and the pool share fxSP as registry rows) is on prod or ships with it
  • executed: 2026-10-04

What it changes for a user, in one line: a wallet that takes fxSAVE's fee-free exit keeps the value on its page through the cooldown, still listed as fxSAVE under Variable rate assets but marked In settlement and worth what the claim will pay, and its statement reads one redemption ("Redemption requested", then "Redemption paid" at what arrived) instead of a withdrawal and, an hour or more later, a fresh deposit.

What it does, and what it leaves.

  • Code only. The escrow class registry gains its seventh class; the escrow stream gains two filters (fxSAVE's RequestRedeem / Claim, the f(x) pool's Redeem) and one certificate key (fxSAVE); the snapshot pass reads every wallet's holding contract and its request at the pool; the derivation writes each redemption's movements (the escrow stream, its f(x) class and the movements). The two activity labels it reads are renamed for every class ("Redemption in settlement" is now "Redemption requested", "Redemption settled" is now "Redemption paid"); nothing else about the other six classes moves.
  • The live ingester scans the two new filters from its own cursor as soon as it restarts on the release. The stream's HISTORY below that holds none of their logs until step 4 sweeps it, and the new key (fxSAVE) has no certificate row until step 6 earns it.
  • Between the deploy and step 6 the change fails closed. A wallet whose reading holds an open fee-free request, or whose ledger holds a movement of one (a request or claim the live ingester saw after the deploy), requires a certificate nobody has written yet, so its rebuilt history withholds (the building state, W7 uncertified-scope) until step 6, and then clears on its own. A wallet with neither is unaffected: its past fee-free exits stay booked as they were (a withdrawal and a deposit) until step 7 re-derives it.
  • A redemption that straddles the deploy is booked half old, half new until step 7. Requested before the deploy and claimed after it, its request was derived by the previous release (the fxSAVE burn as money withdrawn: the stream's history holds no request log until step 4) and its claim by this one (the close of an in-transit leg, its arrivals internal, no deposit). The account then reads the whole redemption as money withdrawn that never came back while the value stayed, so its contributions are understated by the redemption's size: withheld until step 6, then served that way until step 7 re-derives the wallet. That is why step 7 takes its wallet list after step 6 and never before the deploy: a list taken earlier misses every wallet that requests between the query and the deploy and every wallet enrolled since, and nothing else re-derives them.
  • The reconciler pages for those wallets until step 6 completes. Between the deploy and step 6 it excludes every enrolled wallet the fail-closed bullet above withholds (its coverage is not certified), and a wallet excluded on two consecutive reconcile ticks (six hours apart) pages, as [fail] ledger-reconcile excluded=… naming the wallet. Run steps 3 to 6 straight after the deploy; those exclusion pages stop on their own once step 6 certifies fxSAVE.
  • Not changed: a wallet holding an in-transit leg of any OTHER escrow class is still refused by the derivation, as before this release (now by the escrow universe rather than the venue terminal).

Prod, in order. Steps 4 to 7 write prod and need the owner's go.

  1. Plan the window, before the deploy. Steps 3 to 6 run straight after the deploy, attended: until step 6 completes, the reconciler can page for every wallet the change withholds (above). Take no wallet list now; step 7 takes it after step 6, so that it holds every wallet whose redemption straddles the deploy and every wallet enrolled since. Steps 4 to 6 are owed whatever that list turns out to hold: the certificate is about the stream, not about any one wallet, and a wallet that takes the exit tomorrow needs it.

  2. The deploy (the release merge). In a release that also carries migration 126, its steps run first (its entry): this class's leg is valued as the pool share, which needs fxSP's registry row, and the movements' payout legs need fxUSD's.

  3. The registry check, read-only:

    bash
    cd /opt/onchain-credit && ETHEREUM_RPC_URL="$(grep ^ETHEREUM_RPC_URL= .env.local | cut -d= -f2-)" \
      npm run verify:escrow-registry

    Exit 0, 7 class(es), 22 assertion(s), and the five new lines read (mainnet, 2026-10-02):

    text
    ok   fx-fxsave-cooldown  base()                 0x65c9a641afceb9c0e6034e558a319488fa0fa3be
    ok   fx-fxsave-cooldown  lockedProxy(address)[0xc693b4ffb338579467a541b2bf267b1955870920] 0x73e3eb4541f033e304bc16d32af77aeef6e03a05
    ok   fx-fxsave-cooldown  yieldToken()           0x085780639cc2cacd35e474e71f4d000e2405d8f6
    ok   fx-fxsave-cooldown  stableToken()          0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48
    ok   fx-fxsave-cooldown  redeemCoolDownPeriod() 3600

    The lockedProxy line reads the holding contract f(x) STORED for one recorded holder at that holder's first request, and a stored address never changes for its holder, so this line cannot show an upgrade of the holding contract's code (that would move only new holders' addresses). A drift on it means the stored mapping itself changed: stop before step 4 and find out why. What protects the class against a code change is the cross-check on every read: the snapshot reader reads the stored contract beside the one the recipe derives and reads the stored one wherever the two differ, and the archive anchor refuses rather than guess, so that wallet withholds where an anchor is asked, never a wrong figure. After any fxSAVE upgrade, re-check the recipe on a holder whose first request postdates it (or re-extract the creation code from the new implementation, as was done on 2026-10-02). redeemCoolDownPeriod is report-only: a changed value (f(x)'s admin can set up to 7 days) prints as moved with the chain's value, adds a reported, not held line and still exits 0, and the ingester keeps scanning, because the cooldown only sets how long a request waits and changes no figure.

  4. GATED: sweep the escrow stream from the floor to its live cursor, so the two new filters' history is ingested (attended; the backfill runner, idempotent upserts, archive RPC; the other four filters re-read rows that are already stored):

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    TO=$(psql "$DATABASE_URL" -tAc "SELECT last_scanned_block FROM onchain_credit.chain_scan_cursors WHERE chain_id = 1 AND scope = 'ledger:escrow'")
    npx tsx scripts/backfill-event-ledger.ts --stream escrow --from 22527558 --to "$TO" --dry-run
    npx tsx scripts/backfill-event-ledger.ts --stream escrow --from 22527558 --to "$TO"

    An explicit --from is a hole repair, so it writes events, receipts and the swept-progress record for every key (fxSAVE's included) and claims nothing complete. Check, read-only, that fxSAVE's two events arrived: SELECT topic0, count(*), min(block_number), max(block_number) FROM onchain_credit.raw_events WHERE chain_id = 1 AND stream = 'escrow' AND address = '0x7743e50f534a7f9f1791dde7dcd89f7783eefc39' GROUP BY 1 returns two rows, from near the floor.

  5. GATED: re-measure the stream's history band over the six filters, from the second provider (the recorder; the frozen 294,592 counts the first four filters alone, so the completion in step 6 would refuse against it):

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    LEDGER_VERIFY_RPC_URL=<second provider> \
      npx tsx scripts/record-ledger-backfill-band.ts --stream escrow --to 25828233 \
        --note "<date> f(x) fee-free exit joins the escrow stream" --window 5000 --dry-run
    # then the same with --confirm in place of --dry-run

    Expect 294,592 plus f(x)'s three pairs over [22,527,558, 25,828,233] (a few thousand).

  6. GATED: the completion run, which judges the corpus against step 5's band and promotes the certificate, the new key included:

    bash
    npx tsx scripts/backfill-event-ledger.ts --stream escrow
    npx tsx scripts/backfill-event-ledger.ts --verify --stream escrow   # read-only

    Expect 5 coverage row(s) stamped live from 22527558 and a verify PASS; SELECT address, from_block, status FROM onchain_credit.event_coverage WHERE chain_id = 1 AND stream = 'escrow' lists five rows, fxSAVE's among them, all live from 22527558. A refusal publishes nothing and names its reason; do not answer it by re-running (the runbook's rule).

  7. GATED: after step 6, take the wallet list (read-only), then re-derive those wallets from the floor, and only those. Take the list here and never earlier (the straddle case above). The wallets that ever burned fxSAVE: every fee-free request burns it (and so does the instant exit, so this is a superset), and the wallet-token stream stores every transfer touching an enrolled wallet, registered token or not:

    sql
    -- read-only: the wallet list for steps 7 and 8
    WITH w AS (SELECT uid, '0x000000000000000000000000' || substr(uid, 3) AS t FROM onchain_credit.accounts)
    SELECT w.uid
      FROM w
     WHERE EXISTS (SELECT 1 FROM onchain_credit.raw_events e
                    WHERE e.chain_id = 1 AND e.stream = 'wallet-token'
                      AND e.address = '0x7743e50f534a7f9f1791dde7dcd89f7783eefc39'
                      AND e.topic0 = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
                      AND e.topic1 = w.t
                      AND e.topic2 = '0x0000000000000000000000000000000000000000000000000000000000000000')
     ORDER BY 1;

    Zero rows means the rest of this step and step 8 have nothing to do. With the full wipe of every wallet the owner expects at this release, step 7 has nothing to re-derive: the query then lists only wallets that enrolled after the wipe and before step 6 and burned fxSAVE (a wallet enrolled after step 6 is derived whole by this release over a certified history). Run it anyway, and re-derive whatever it lists. Queue one rederive per listed wallet with the insert the native-ether release uses (its step 7), restricted to the list (AND a.uid = ANY ('{<the list>}'::text[])), and read it done from portfolio_derive_jobs. Never before step 6: a re-derived wallet with a past fee-free exit then holds escrow movements whose certificate is missing, and withholds. A full re-derivation is the safe form here: the escrow adapter re-hydrates an open redemption from the rows BELOW a range, and below a range derived by the previous release there are none.

  8. Check, read-only, per re-derived wallet: its escrow movements and their groups,

    sql
    SELECT block_number, venue, position_key, kind, amount_raw, link_id
      FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND wallet = '<wallet>' AND link_kind = 'escrow'
     ORDER BY block_number, log_index, seq;

    Every redemption is one link_id (esc:1:0x7743…efc39:<wallet>:<block>) holding an internal_out on wallet:token:0x7743… and an internal_in on escrow:fx-fxsave-cooldown:<wallet> at each request, and at its claim an internal_out on the escrow leg (its to_balance 0) beside the arrivals' internal_in rows. No transfer_out of fxSAVE to the zero address and no transfer_in of the claim's fxUSD or USDC remain for that wallet, and the reconciler's line for it (npx tsx scripts/ops/reconcile-ledger.ts --wallet <wallet>) is clean.

    The stretch no reading read. Readings taken before the deploy never read the class, so a redemption that was OPEN at one of them has its movements in the re-derived ledger and no in-transit leg in that reading. Most cooldowns open and close inside one six-hour interval and need no reading at all; one that spanned a reading withholds that interval (W1 unread-endpoint) and the reading audit reports the leg unread. The reading top-up fills the readings a wallet's registration replay wrote; a wallet on step 7's list with such a stretch is a finding for Fred.

  9. Record executed: with the date, step 3's output, step 6's coverage lines and step 8's rows.

Executed 2026-10-04 (Fred: "instruct an opus 5.5 agent to do it all"; v0.76.0, release PR #1012, merge 40d75b1f, deploy run 37187814380 green at 08:06:56Z), summary lines per step. Step 1: steps 3 to 6 ran straight after the deploy, attended; no wallet list was taken before it. Step 2: the deploy (126 on prod since v0.75.0). Step 3 at 08:07Z from the prod checkout: exit 0, [escrow-registry] 7 class(es), 22 assertion(s), the five fx-fxsave-cooldown lines exactly as above (redeemCoolDownPeriod() 3600, no moved line), OK — 22 assertion(s) match the chain (a read-only forecast from the staging checkout at 05:58Z, before the merge, read the same). Step 4: TO 26117623 (the escrow cursor at 08:07Z); the dry run plan [22527558,26117623] · 72/72 window(s), 5 certificate key(s); the run 08:07:41Z to 08:11:21Z, exit 0, range retained as raw evidence only: bottomed by an explicit --from 22527558, so this run is a repair, not a completion, range done [22527558,26117623] · 6153 new row(s); fxSAVE's two events, 0x3a4aaf3c… 1868 rows from block 22528502 and 0x1836092b… 1762 from 22528671 (both through 26111481), and the pool's 0x215abfcd… 2523 from 22527614 (6153 together). Step 5, from the second provider with --window 5000: the dry run 08:11:53Z to 08:21:05Z, independence established against the sweep's own scan receipts, measured 300500 claimed row(s) (300500 raw log(s), 3966 chunk(s)) over [22527558,25828233], the stored corpus over the same range 300500 (294,592 plus f(x)'s 5,908: fxSAVE 3474, the pool 2434); --confirm 08:21:43Z to 08:30:43Z, recorded escrow=300500 over [22527558,25828233] (superseding 294592). Step 6 at 08:30:53Z: conditions 1 to 4 pass (300500 row(s) over [22527558,25828233] vs [300500,300500], 116 receipt(s), no gap, the digest of [25427558,25477557] against the second provider, 2 anchor(s) present), 5 coverage row(s) stamped live from 22527558, complete [22527558,25828233] · 0 new row(s), exit 0 (its rolled out AFTER the shadow build … re-derive the affected tracked wallets note had no tracked wallet to act on); --verify: 5/5 declared address(es) live from the floor, verify PASS · run 928b443cb7fb; event_coverage lists the five addresses live from 22527558, fxSAVE's 0x7743…efc39 new among them, beside the stream's * marker (live since 2026-08-25). Step 7 at 08:31:57Z: the list query returned 0 rows (prod has had 0 accounts since the 2026-10-03 wipe), so nothing was re-derived and step 8 had no wallet to check. The ingester's escrow scan stayed live throughout (registry verified against chain · 22 assertion(s) match, no cycle error).

Staging. Steps 3 and 8's queries are read-only and safe there; the nightly reseed restores prod's raw_events and event_coverage, so a staging sweep is undone by the next reseed and proves nothing about prod (staging's data is a reseed).

Rollback. A code rollback does not roll back the database. The previous release reads no fx escrow leg and derives no escrow venue, so a wallet holding the leg's rows is refused by its venue terminal until it is re-derived under the previous code (which books the burn and the arrivals as transfers again). The ingested fx logs and the fxSAVE certificate row are inert under the previous code: it scans and requires neither.

The contract release, step 2: the stored value columns go (migration 129): prod steps, in order ​

  • belongs to: issue #981, step 2 (PR #1011, branch feat/981-step2-drop-value-columns), migration 129 (-- DESTRUCTIVE, hand-run)
  • executed: 2026-10-04

What it changes for a user, in one line: nothing on screen. Every value the page shows has been computed at read since v0.71.0; this release removes the two frozen figures a reading still carried beside its facts, and the derivation code the ledger worker replaced in step 1.

What it does, and what it leaves.

  • Migration 129 (scripts/sql/129-drop-reading-value-columns.sql) drops value_market and value_redemption from portfolio_position_snapshots, from the parent and every monthly partition: a catalog change, no row is rewritten. Its acceptance block raises unless both are gone everywhere, and a second run drops nothing. Line 1 is -- DESTRUCTIVE, so migrate.sh never applies it (a deploy skips it on both boxes): it is run BY HAND, after the deploy of this release. Its line 2, -- FIXTURE-APPLIES, is read only by the test fixture's builder, which applies it so every suite runs against the schema after the drop (processes).
  • No writer or reader names the two columns. A reading's value is computed at read from its quantity, its rate facts and the series, or withheld (both lines null, counted as withheld-readings= on the reconciler's line, and paged by the hourly check's ledger-audit arm when one is recorded) where a rate its value reads has no fact (the loader rule); the writers produce none since migration 128. A movement and a pre-window PT fill keep their two columns, served only where no fact answers them (factless=M/F). The census counts a reading as valued, unvalued or withheld; the rate-facts backfill fills movements and fills only; the guarded snapshot re-mark (remark-snapshot-marks.ts) is deleted, and the Fluid dust re-mark and the ghost adjudicator restate a reading's quantity only.
  • The coverage restatement's ether hold is lifted (issue #989, its entry): the reading audit values a reading at read, in its own book, so an EXCLUDED -> ETH widening is restated like a dollar one.
  • The old derivation paths are deleted, with the constant that selected them (WORKER_OWNS_DERIVATION): the page load's inline merge, the registration replay's, the 6h tick's per-wallet pass and the re-derivation trigger's inline launch, and the worker's pre-flip branches. The deploy's restart script fails the run on a missing worker whatever the checkout (the ledger worker).
  • The W9 / W10 residue is gone (the contract list).
  • What the release writes by itself: one restatement, if any widening is held. No migration runs on the deploy and nothing is removed. With the ether hold lifted, the worker's first coverage-restatement turn after its restart restates any EXCLUDED -> ETH widening it had been holding (the readings of an asset that came into the ether book), and queues a rederive of each wallet it touched, as it does a dollar one. After the wipe expect none: before the deploy the worker's log has no [restate] held back … (-> ETH): an ether-book widening waits for the release that drops the frozen value columns line, and after it the first pass prints [restate] nothing to restate: … or a [restate] done: … line with 0 held back (pm2 logs creddit-ledger-worker --lines 2000 --nostream | grep '\[restate\]' | tail -5; the coverage restatement). A restated wallet prints its own [restate] <wallet> <asset>: N reading(s) restated EXCLUDED -> ETH, … and rederive job #<id> queued lines: record them. The drop (step 4) is the release's one prod write by hand, and it is the point of no return: after it the two figures exist only in step 3's dump and the daily backup (/opt/backups, 02:15Z, 14 days, same disk).

Why the drop runs AFTER the deploy, never before. The release before this one (v0.75.0) names both columns in every reading INSERT, so dropped under it every page load's live reading, every 6h checkpoint and every registration replay would fail at its first write. This release names neither, so the columns can go once it is live, and a code rollback after the drop needs them back first (below).

The population at the drop. The owner wiped every account before this step (2026-10-03 16:21Z, the wipe), so the readings prod holds at the drop are only those written since, by writers that keep every rate their value reads (128): none is withheld, and the two columns hold nothing a served path reads.

Preconditions, read on the day.

  1. The two columns are nullable on prod (they have been since 043): this release's writers omit them, so a NOT NULL would refuse every reading between the deploy and the drop.

    bash
    sudo -u postgres psql -At -d creddit -c "SELECT attname, attnotnull, atthasdef FROM pg_attribute \
      WHERE attrelid = 'onchain_credit.portfolio_position_snapshots'::regclass \
        AND attname IN ('value_market', 'value_redemption') AND NOT attisdropped ORDER BY 1"
    # value_market|f|f
    # value_redemption|f|f
  2. Staging has run the drop (below).

  3. No prod reading would be withheld, read BEFORE the release PR merges (PR #1011 review, SF-2). It is the release, not the drop, that stops serving a reading's stored figure: from its deploy every page computes a reading's value or withholds it, and a withheld one shows no value on its row and drops out of its book's totals and chart (a book whose every holding is withheld reads $0 there). So the count is read with THIS release's code against prod, before prod runs it: the census, read-only, from the staging checkout (the release's code once the PR is merged into staging) pointed at prod's database, as the 124 plan step did:

    bash
    cd /opt/onchain-credit-staging && ( set -a && . /opt/onchain-credit/.env.local && set +a \
      && npx tsx scripts/ops/value-parity.ts --db-url "$DATABASE_URL" )

    Expect reading lines: valued N, unvalued U, withheld (no rate fact) 0 (it counts a reading's two lines; 0 wallet(s) is a valid answer after the wipe). Cross-check, free, from the log prod already writes: the newest 6h reconciler run under v0.75.0 counts the same readings in the first field of factless= (a reading v0.75.0 serves its stored figure for want of a fact is exactly one this release withholds), so every wallet's line reads factless=0/…:

    bash
    grep 'ledger-reconcile: .* values=' /tmp/onchain-credit-cron/onchain-credit-refresh-ledger-reconcile.log \
      | tail -n 40 | grep -v ' factless=0/'   # prints nothing

    A withheld reading is a STOP: do not merge the release PR, and report the wallets and legs to the owner. Step 2 below stays the drop's own gate, read again after the deploy.

Prod steps, in order. Steps 3 and 4 write prod and need the owner's go.

  1. The release PR and the deploy (merge staging into main). The deploy's migrate.sh skips 129 (-- DESTRUCTIVE); the release carries no other migration. Its restarts load the release in the app, the ingester and the worker. The columns are still there and nothing names them, so the deploy is an ordinary one: read the worker's start line and the next page load's job as after any release (the ledger worker).

  2. The census, read-only, against prod, with this release's code (the prod checkout, after the deploy):

    bash
    cd /opt/onchain-credit && set -a && . ./.env.local && set +a
    npx tsx scripts/ops/value-parity.ts --db-url "$DATABASE_URL"

    Expect reading lines: valued N, unvalued U, withheld (no rate fact) 0, and served stored (no rate fact) 0 on the receipt and fill lines; after the wipe the population is the wallets registered since (none at all is a valid answer: 0 wallet(s)). It is precondition 3 read again, over the readings written since: a withheld reading is one the page cannot value, so STOP and report it, since the drop removes the stored figure a rollback to the release before would show again.

  3. GATED: the dump, data-only, of the one table the drop touches. --table-and-children (pg_dump 16) because the table is partitioned and -t alone dumps the empty parent:

    bash
    ts=$(date -u +%Y%m%dT%H%M%SZ)
    sudo -u postgres pg_dump -d creddit --data-only --table-and-children \
      onchain_credit.portfolio_position_snapshots > /root/backup-readings-129-$ts.sql
    grep -c '^COPY ' /root/backup-readings-129-$ts.sql                    # one per partition
    sudo -u postgres psql -At -d creddit -c "SELECT count(*) FROM onchain_credit.portfolio_position_snapshots"

    The rows the COPY blocks hold must add up to the count (awk '/^COPY /{c=1;next} /^\\\.$/{c=0} c{n++} END{print n}' over the file).

  4. GATED: migration 129, BY HAND, from the prod checkout at the release's merge commit (the 124 / 125 single-file pattern), just after an hourly check (:05) and outside a tick (:50 at 00, 06, 12 and 18 UTC):

    bash
    git -C /opt/onchain-credit rev-parse HEAD                      # = the release PR's merge commit
    git -C /opt/onchain-credit status --porcelain -- scripts/sql   # prints nothing
    f=129-drop-reading-value-columns
    sudo -u postgres env "PGOPTIONS=-clock_timeout=10s -cstatement_timeout=300s" \
      psql -v ON_ERROR_STOP=1 -X -q -1 -d creddit -f /opt/onchain-credit/scripts/sql/$f.sql \
    && sudo -u postgres psql -q -d creddit -c "INSERT INTO onchain_credit.schema_migrations(filename) \
         VALUES ('$f.sql') ON CONFLICT DO NOTHING"
    sudo -u postgres psql -At -d creddit -c "SELECT count(*) FROM onchain_credit.schema_migrations WHERE filename = '$f.sql'"   # 1
    sudo -u postgres psql -At -d creddit -c "SELECT count(*) FROM pg_attribute a JOIN pg_partition_tree('onchain_credit.portfolio_position_snapshots') t ON t.relid = a.attrelid WHERE a.attname IN ('value_market', 'value_redemption') AND NOT a.attisdropped"   # 0

    It holds ACCESS EXCLUSIVE on the table for the moment it takes; one that aborts on lock_timeout (a writer held the table: a page load's live reading, the worker's audit) changed nothing and is run again when quiet.

  5. Verify.

    • The app answers: curl -s -o /dev/null -w '%{http_code}\n' https://creddit.xyz/portfolio prints 200.
    • A sign-in writes a reading: the owner signs in (or presses Synchronize) and the refresh answers refreshed: true; its reading is stored: SELECT count(*) FROM onchain_credit.portfolio_position_snapshots WHERE wallet = '<wallet>' AND updated_at > now() - interval '10 minutes' is at least 1, and the app's log has no column "value_market" error (grep -c 'value_market' /root/.pm2/logs/onchain-credit-error.log does not grow).
    • The hourly check's arms are ok at the next :05 (tail -n 12 /tmp/onchain-credit-cron/onchain-credit-check-ingester-freshness.log): the ledger-audit arm's ok line, with no withheld reading(s) page and no [partial] ledger-audit line before it.
    • The next 6h tick writes its checkpoint: [portfolio] wrote N snapshot rows, liveTipsRetired=K …, v2 sweep: … enqueued, exit 0; the worker's sweep jobs -> done; and the reconciler's next run prints withheld-readings=0 and factless=0/0 on every wallet's line.
  6. Record executed: with the date, the release PR and its merge commit, step 2's census line, step 3's file and its COPY and row counts, step 4's two counts, and step 5's tick line.

Executed 2026-10-04 (Fred: "instruct an opus 5.5 agent to do it all"; v0.76.0, release PR #1012, merge 40d75b1f, deploy run 37187814380 green at 08:06:56Z), summary lines per step. Staging: #1011 merged into staging at 05:54:41Z (8e503a82); its deploy (run 37181231722) printed SKIP destructive (needs --allow-destructive): 129-drop-reading-value-columns.sql; 129 by hand on creddit_staging at 05:56:52Z from the staging checkout at 8e503a82: schema_migrations 1, the partition tree's attribute count 0, the staging app 200 and its drain clean after it; the version bump f0d9fecd's staging smoke (every page): 186 passed, 321 skipped, 0 failed. Preconditions, read at 05:52Z and again at 08:05Z: (1) value_market|f|f, value_redemption|f|f; (2) above; (3) the census from the staging checkout at f0d9fecd against prod: 0 wallet(s), reading lines: valued 0, unvalued 0, withheld (no rate fact) 0, exit 0, and the reconciler cross-check printed nothing (its last 40 values= lines, all from before the wipe, read factless=0/…; the runs since hold no wallet). The worker's log held no held back … (-> ETH) line before the deploy. The release PR's CI (run 37181377942) green on attempt 2: attempt 1's e2e-interaction (desktop-1360) failed one spec, a build landing into the uncertified tail brings the WHOLE portfolio (a 15 s route.fetch timeout of the load-sensitive building-state spec), and the job's re-run passed (474 passed, 1 flaky); narrow-900 474 passed, 1 flaky. Step 1: merged at 08:05:45Z, after the 08:05Z check; Deployed 40d75b1f at 2026-10-04T08:06:56Z, the app, the ingester and the worker restarted on 0.76.0, 129 not applied by the deploy; the worker starting as ubuntu-8gb-nbg1-1:4171910 · with the sync lane at 08:06:57Z, and its first pass [restate] nothing to restate: every stored reading agrees with the registry's book (16ms) (no widening was held, so none was restated and no rederive queued). Step 2 at 09:00:42Z: value parity: 0 wallet(s), 0 reading(s), 0 receipt(s), 0 pre-window fill(s), reading lines: valued 0, unvalued 0, withheld (no rate fact) 0, served stored (no rate fact) 0 on the receipt and fill lines, exit 0. Step 3 at 09:00:47Z: /root/backup-readings-129-20261004T090047Z.sql (5,858 bytes, sha256 e7e282e6…), 11 COPY blocks (one per partition, _202601 to _202611, each naming both columns), 0 rows in them, the table's count 0. Step 4 at 09:05:29.9Z, once the 09:05Z check had finished: HEAD 40d75b1f28b268b12af3521f3a555f34f11d96ca (the merge commit), scripts/sql clean; the file under psql -1 exit 0 in 0.15 s, the INSERT recorded; schema_migrations count 1 (applied 09:05:30Z), the partition tree's attribute count 0. Step 5: https://creddit.xyz/portfolio 200 at 09:05:30Z; value_market / value_redemption in the app's error log 0 before and 0 after, and in no process's log since; the 10:05Z hourly check, the first after the drop: ledger-audit: ok: no unexplained adjustment, no leg unread twice, no withheld page and no [partial] line, ledger-derive-lag: ok. A sign-in at 11:31Z enrolled three wallets (0x46a2… and 0xaf35… empty, 0xe159… holding): 0xe159…'s registration stored 256 readings at 11:41Z (enrol #841 and audit #842 done, 0 adjustments), and the census over them read reading lines: valued 512, unvalued 0, withheld (no rate fact) 0, receipts equal 32, differs 0. The 12:50Z tick: [portfolio] wrote 8 snapshot rows, liveTipsRetired=0 (derived <= 26119033, ledger lag 1), v2 sweep: 3 sweep job(s) enqueued over [26111834,26119033], exit 0; the worker's three sweeps (#844 to #846) -> done and v2 tick cursor -> 26119010. The 13:05Z check ok on all four arms. The 13:30Z reconciler: wallets=3 reconciled=3 excluded=0, 0xe159…'s line values=computed readings=264 withheld-readings=0 receipts=16 differ=0 … factless=0/0 (the two empty wallets not comparable yet), no page. Owed: step 5's page-load half. The post-enrolment page-load syncs that ran (#838, #839, done) were the two empty wallets', which store no reading, and 0xe159…'s only one (#840) ran before its enrolment (partial), so a Synchronize on a holding wallet answering refreshed: true with its live reading stored waits for the owner's next visit. Standing since the 2026-10-03 wipe and cleared by the sign-in, none of them this release's: the hourly check's ingester-feed-lag page (the wallet-token feed held while no wallet was enrolled; feeds ok from 12:05Z), the reconciler's measured-nothing page (none at 13:30Z), and the 12:05Z check's ledger-derive-lag page (No sweep has completed for 23h14m: no tick had a wallet to sweep between the wipe and the sign-in), which the 12:50Z tick's sweeps cleared.

Staging, before the release ​

  1. Merge the PR into staging. The staging deploy applies nothing of it to the database (129 is -- DESTRUCTIVE); the code it deploys names neither column, so it runs on the schema as it stands.

  2. Run 129 by hand on creddit_staging, after that deploy (never before it: the code the staging box ran until then named both columns), from the staging checkout:

    bash
    git -C /opt/onchain-credit-staging rev-parse HEAD                      # = the merge into staging
    f=129-drop-reading-value-columns
    sudo -u postgres env "PGOPTIONS=-clock_timeout=10s -cstatement_timeout=300s" \
      psql -v ON_ERROR_STOP=1 -X -q -1 -d creddit_staging -f /opt/onchain-credit-staging/scripts/sql/$f.sql \
    && sudo -u postgres psql -q -d creddit_staging -c "INSERT INTO onchain_credit.schema_migrations(filename) \
         VALUES ('$f.sql') ON CONFLICT DO NOTHING"
    sudo -u postgres psql -At -d creddit_staging -c "SELECT count(*) FROM onchain_credit.schema_migrations WHERE filename = '$f.sql'"   # 1
  3. The nightly reseed brings the columns back, until prod has dropped them: it restores prod's schema and its schema_migrations ledger (staging's data is a reseed), so after 03:00 staging has the two columns and no 129 row again. That is harmless (the code names neither column), and it is why step 2 is a rehearsal of the drop rather than a state staging keeps. To hold the dropped schema across a validation window, touch /root/.reseed-paused before it and rm -f /root/.reseed-paused after. Once prod has run 129, every reseed carries the dropped schema.

  4. Exercise it: the owner's sign-in and Synchronize against the release's code, with a hand-run worker draining (staging runs none: LEDGER_WORKER_EXIT_WHEN_IDLE=1 bash scripts/worker/run-worker.sh from the staging checkout): refreshed: true, the reading stored, and the page's figures as before.

Rollback ​

Before step 4 (the drop) a rollback is an ordinary code revert: the columns are still there, and the release before fills them in every reading it writes.

After step 4 the drop is the point of no return, and a code rollback to v0.75.0 needs the two columns back BEFORE its deploy (its writers name them), with the stored figures of the readings the dump holds. With the worker stopped (pm2 stop creddit-ledger-worker && pm2 save) and between ticks:

bash
# 1. the columns back, as 043 made them (nullable numeric), and 129 out of the ledger
sudo -u postgres psql -v ON_ERROR_STOP=1 -X -d creddit -c "ALTER TABLE onchain_credit.portfolio_position_snapshots \
  ADD COLUMN IF NOT EXISTS value_market numeric, ADD COLUMN IF NOT EXISTS value_redemption numeric"
sudo -u postgres psql -q -d creddit -c "DELETE FROM onchain_credit.schema_migrations WHERE filename = '129-drop-reading-value-columns.sql'"
# 2. the figures back from the dump: every COPY block into one scratch table, then by key
f=/root/backup-readings-129-<ts>.sql
sudo -u postgres psql -v ON_ERROR_STOP=1 -X -d creddit -c "CREATE UNLOGGED TABLE onchain_credit.r129_restore \
  (LIKE onchain_credit.portfolio_position_snapshots)"
sed -E 's/^COPY onchain_credit\.portfolio_position_snapshots[A-Za-z0-9_]* /COPY onchain_credit.r129_restore /' "$f" \
  | sudo -u postgres psql -v ON_ERROR_STOP=1 -X -q -d creddit
sudo -u postgres psql -v ON_ERROR_STOP=1 -X -d creddit -c "UPDATE onchain_credit.portfolio_position_snapshots s \
  SET value_market = r.value_market, value_redemption = r.value_redemption FROM onchain_credit.r129_restore r \
  WHERE s.chain_id = r.chain_id AND s.wallet = r.wallet AND s.venue = r.venue AND s.position_key = r.position_key \
    AND s.snapshot_ts = r.snapshot_ts"
sudo -u postgres psql -q -d creddit -c "DROP TABLE onchain_credit.r129_restore"
# 3. then the revert's deploy, then the worker

The UPDATE count is the dump's row count less any row deleted since (a live tip a checkpoint retired). A reading written between the drop and the rollback has no stored figure: the release before computes its value at read from its facts as this one does, so it shows the same numbers.

Watch list ​

  • A withheld reading pages, and shows as $0, not as a gap (PR #1011 review, SF-3). From this release a reading whose value reads a rate no fact answers has no figure to fall back on: its row shows no value, and its book's totals and chart sum without it, so a book whose every holding is withheld at a point reads $0 there (the headline, and the chart dropping to 0), with nothing telling the reader it is missing. The writers record none since 128, so the hourly check's ledger-audit arm pages each one recorded since its last look ([fail] ledger-audit: N withheld reading(s): fix the writer that kept no rate fact; first=<wallet> <leg> @<block>, …), and the reconciler counts them per wallet (withheld-readings=). A decision for Fred, open: a withheld reading should show as a gap in the totals and the chart, not as 0 (the curve publishing its point as missing, as it already does where the accrual line has nothing to state). Not built by this release (the plan, §11).
  • The hourly check now values readings (SF-1): its ledger-audit arm installs the database's registry through its own connection at every look and values the readings recorded since the last one. A [partial] ledger-audit: … wallet(s) not valued … line (exit 1) means it could not: once is a blip, every hour is a valuation that cannot run (the error is on the line).

The reconciler judges the bookings the page serves (issue #988, no migration): re-set the withhold budget ​

  • belongs to: issue #988 (branch feat/988-reconciler-shared-construction), no migration; it presumes the contract release, step 2 (v0.76.0) is on prod
  • executed: pending

What it changes for a user, in one line: nothing on screen. The 6h ledger check now judges the figures the page shows instead of a second, unmarked derivation of them, so it stops paging four times a day on its own artefact on principal-token holdings.

What it does, and what it leaves.

  • Code only. The reconciler (the scheduled refresh-ledger-reconcile.ts and the hand reconcile-ledger.ts) runs the page's own construction before its engine (why): the PT accrual marks and the financed-group rule, over the token registry, the Pendle market universe and each held market's factor series, read inside each wallet's snapshot. Its right-hand side takes the same marked values as input.
  • What moves in the run's lines: the W2 unpriced-input rows on principal-token legs (evidence endpoint:value_redemption-null, two per interval) leave the count wherever the page values the leg (on 2026-09-29: 296 of prod's 363 declined rows; 102 of 102 on 0xea88…, 94 of 109 on 0xe51d…, 90 of 152 on 0xb47c…). The comparisons they hid join checked=. What stays declined on such a leg is the page's own withhold (the reason the page logs: pt-factor-unavailable, pt-lot-unvalued, …). Expected remainder on the test wallets: real gaps only (0xb47c…'s PT-USD3 accrual factor, USD3's unpriced hours, unread plain-token stretches).
  • What it does NOT check: the PT mark itself. Both sides sum the same mark, so on a principal token's accrual line the identity verifies the bookkeeping over the curve and not the curve (maturity reaching q × f, a buy netting to zero, no jumps). Out of scope by the owner's call.
  • A failed registry read is now fatal for the run (exit 1), where the page degrades to a dash. The line names the wallet and the read: [fail] ledger-reconcile fatal read-time registry read failed for <wallet> at <relation>, so the run measured nothing: <cause>.
  • The budget is NOT changed by the deploy. Prod's PORTFOLIO_RECONCILE_WITHHOLD_BUDGET is 1 (set before this release); it is re-set by hand from the first run after it, step 3.

Steps, in order.

  1. Before the release PR merges, keep the baseline: the last scheduled run's lines on prod (the population withholds= / checked=, and each budget total line).

    bash
    grep -a "ledger-reconcile" /tmp/onchain-credit-cron/onchain-credit-refresh-ledger-reconcile.log | tail -80
  2. The first scheduled run after the deploy (30 1,7,13,19 * * *): read the same lines. Expect withholds= to fall and checked= to rise by the PT accrual comparisons, no fatal line, and on each test wallet a budget total count at or below the remainder above. Stop and report if a residual line names a principal token's accrual line: it is the first time the identity has been asked about that line, so it is a finding about the engine's bookkeeping, not noise to budget away. A fatal … read-time registry read failed for <wallet> at <relation> line means the run measured nothing: read the cause at its end (a missing relation, a timeout, a dropped connection) and re-run by hand once it is fixed.

  3. Re-set the budget from that run, only with Fred's explicit go (both halves touch prod: a read-only hand run against its database, then an edit of its environment), by the runbook's procedure: the hand run at budget 0, the per-wallet figures, Fred's choice of number, one line in /opt/onchain-credit/.env.local. The next scheduled run reads it.

  4. Record here: the date, the before and after withholds= / checked=, each test wallet's remainder by shape, and the number chosen.

Partial record, 2026-10-05 (still pending: steps 2 to 4). Released in v0.77.0, release PR #1021 (head release/v0.77.0, cut from staging at da447268), merge 63ce93ba, tag v0.77.0, deploy run 37292432839: Deployed 63ce93ba at 2026-10-05T09:49:22Z, the app, the ingester and the worker online on 0.77.0, the app 200. Step 1, the baseline: the last scheduled run before the merge (07:30Z) ledger-reconcile: wallets=3 reconciled=3 excluded=0 uncertified=0 checked=630 book-checked=210 withholds=0 notes=0, no budget total line (prod's population since the 2026-10-03 wipe is three wallets, one holding: 0xe159…, withheld-readings=0 … factless=0/0; 0x46a2… and 0xaf35… not comparable yet). The budget stays 1. Step 3's read-only half, run at 10:53Z on the released code (budget 0, --json, exit 0): population identityChecked=648 bookIdentityChecked=216 withholds=0, no identity failure, no measuredNothing; every wallet withholdsByShape={} and no budget breach, so no wallet has a per-day line (each passes at 0). No wallet on prod holds a principal token today, so the PT accrual comparisons this release adds were not exercised by either run. Owed: step 2 (the first scheduled run after the deploy, 13:30Z on 2026-10-05) and Fred's choice of number (step 3's second half, step 4).

Rollback: revert the release. The old checker returns, and with it the PT artefact rows. If the budget was re-set in step 3, restore 1 (with Fred's go) and expect the pre-#988 paging (at 1 the old checker paged every run, four times a day); unsetting it instead silences the total-count page, while the two zero-budget classes (W6, W8) still page.

The page at the chain's tip: the pending band (issue #965, no migration): first deploy ​

  • belongs to: issue #965 (branch feat/965-pending-tip), no migration; it presumes the contract release, step 2 (v0.76.0) is on prod, so the worker is the only writer of derived rows
  • executed: 2026-10-05

What it changes for a user, in one line: a movement shows on /portfolio about a minute after its block instead of about 14, and the "Updated" time moves with it; nothing new is drawn.

What it does. The ingester reads every stream a second time, provisionally, up to two blocks behind the head (the pending band); the worker derives that band as 'provisional' rows; the page load reads at the band's top. The reading audit stays on settled rows, and a reorg in the band is restated by the reorg sweep and the continuous producer (reorg repair). New state: the ledger-pending:<stream> cursors and the per-wallet …:settled-through records in chain_scan_cursors; no table, no column.

Environment: LEDGER_PENDING_MARGIN_BLOCKS (default 2, nothing to set) and LEDGER_PENDING_MAX_BLOCKS (default 128, the derive-lag arm's bound), both in the variable table. If the margin is ever set, it is set in the one /opt/onchain-credit/.env.local both the ingester and the app read, and both are restarted.

Steps, in order (prod; staging runs no standing ingester, so there the band exists only during an attended ingester hand-run).

  1. The deploy restarts the ingester and the worker as every deploy does. Within two cycles the ingester log carries one band line a cycle:

    bash
    pm2 logs creddit-event-ingester --lines 200 --nostream | grep -a "\[ingester/pending\]" | tail -3
    # [ingester/pending] band read to <head - 2> (from <settled + 1>) on 14 stream(s), wrote N row(s)

    A [ingester/<stream>] pending scan error line repeating every cycle on one stream holds the provisional tip at that stream (the page then reads where it did before); read its cause.

  2. The next hourly alarm (5 * * * *): the derive-lag ok line now ends its producer clause with pending band N block(s), N about 62. Past 128 it pages (deployment).

  3. A test wallet's stamp: open /portfolio for a tracked wallet; the "Updated" time is within about a minute or two of the chain's newest block time, not ~14 minutes behind it.

  4. Watch for a reorg in the band over the first days (one or two a week on mainnet): the sweep's line carries pending band restated above block … and the next producer line re-queues the wallets it orphaned rows of. Nothing pages from it.

  5. Record here: the date, the band depth on the first alarm line, and any reorg line seen.

Executed 2026-10-05 (v0.77.0, release PR #1021 (head release/v0.77.0, cut from staging at da447268), merge 63ce93ba, tag v0.77.0, deploy run 37292432839: Deployed 63ce93ba at 2026-10-05T09:49:22Z, the app, the ingester and the worker online on 0.77.0, the app 200), summary lines per step. Step 1: the first cycle after the restart, 2026-10-05T09:49:26: [ingester/pending] band read to 26125374 (from 26125313) on 14 stream(s), wrote 173 row(s), then one band line a minute (53 between 10:00Z and 10:52Z, e.g. 10:52:25 … band read to 26125689 (from 26125685) on 14 stream(s), wrote 16 row(s)); no pending scan error, refusal or error line in the ingester's log since the deploy. Each wallet's …:settled-through record written (26125607 at 10:50Z). Step 2: the 10:05Z hourly check, ledger-derive-lag: ok: heartbeat 0h00m ago, derived through block 26125434; producer 0h00m behind the tip, pending band 62 block(s); 1 queued (oldest none), 0 running, 0 failed, 3 partial in 24h (the three partials are 2026-10-04's first page-load syncs, from before this release). Step 3, read from the data rather than a browser: the page-load syncs of 10:49:06Z (#876 to #878, done) read at block 26125669, the band's top at 10:48:25Z (band read to 26125669), so the stamp was about one minute behind the chain; the audit of that reading (#879) deferred as designed (the wallet's ledger is derived through block 26125607, below the reading's block 26125669) until the settled scan reaches it. Step 4: no pending band restated line in the first hour; the reorg watch runs over the coming days.

Rollback: revert the release. The old ingester stops at head − 64 again and ignores the ledger-pending: cursors and the …:settled-through records (inert rows; leave them, or delete the first with DELETE FROM onchain_credit.chain_scan_cursors WHERE scope LIKE 'ledger-pending:%'). Provisional rows the band left above the settled tip are real movements and are re-derived and relabelled by the old code's passes as the settled tip passes them. For the ~13 minutes after the revert an audit can compare a reading against such rows (the old gate counts a done job's top in full); a disagreement it books is an ordinary audit row the next reading's audit restates.

The two alarm rulings: an unvalued reading is a gap, a failed hourly valuation pages when it repeats (issue #981, PR B, no migration): first deploy ​

  • belongs to: issue #981, PR B (Fred's rulings 2 and 3 of 2026-10-04); no migration
  • executed: 2026-10-05

What it changes for a user, in one line: where a holding's reading cannot be valued, its book's total and chart point show a gap ("partially valued") instead of the rest of the book or $0; the team's hourly page for it, and for the check's own valuation failing twice in a row, is in words.

What the deploy changes. The app serves the gap (M9): the book chart is null at such a point and flagged withheld, the headline's book value at such a newest reading is null with withheld: true, the row names reading-unvalued on both lines, the book card shows its dash and existing reason, and the chart keeps the point a break. The hourly check's ledger-audit arm pages its two findings as its own message (the page) and a failed valuation only at LEDGER_AUDIT_SOURCE_PAGE_AFTER looks in a row; a one-off is a stated line. No served figure moves for a wallet with no unvalued reading, and prod has had none since migration 128 (the census reads withheld (no rate fact) 0), so on today's data nothing on the page changes.

Environment: LEDGER_AUDIT_SOURCE_PAGE_AFTER (optional, read only by the hourly check). Unset means 2, the default and the recommendation (two failed looks in a row, two hours, page); 3 is the only other value it takes (Fred's ruling: two to three hours); anything else reads as 2. Set it, if at all, in /opt/onchain-credit/.env.local: run-cron.sh sources that file at every run, so the next hourly run reads it with no restart.

Restarts: the deploy restarts the app, the ingester and the worker as every deploy does. The app is what serves the gap; the worker's code is unchanged in what it writes (the arm's read module is the worker's, but only the hourly check calls the parts that changed); the hourly check is a cron job and runs the new code from its next run. No crontab change.

Steps, in order (prod; staging pages nothing hourly from this arm unless a reading is recorded there, and its state file is its own, <checkout> keyed):

  1. The first hourly run after the deploy (5 * * * *): the ledger-audit arm's line is the usual ledger-audit: ok: … and no message is sent. Check that its state file is absent or holds nothing open (a clean population writes none):

    bash
    tail -n 6 /tmp/onchain-credit-cron/onchain-credit-check-ingester-freshness.log
    ls -l /tmp/onchain-credit-cron/onchain-credit-check-ingester-freshness.state.json 2>/dev/null || echo "no state (clean)"
  2. If a look cannot value readings (a line ledger-audit: could not value readings this look (1 of 2 in a row before it alerts): …), the state file now holds "source":{"looks":1,…}; a second in a row pages with the arm's own message. Read the reason either way.

  3. Record here: the date, and the first hourly line after the deploy.

Executed 2026-10-05 (v0.77.0, release PR #1021 (head release/v0.77.0, cut from staging at da447268), merge 63ce93ba, tag v0.77.0, deploy run 37292432839: Deployed 63ce93ba at 2026-10-05T09:49:22Z, the app, the ingester and the worker online on 0.77.0, the app 200). LEDGER_AUDIT_SOURCE_PAGE_AFTER not set (default 2). Step 1, the first hourly run after the deploy (10:05Z): ingester-freshness: ok: started 2026-10-05 09:49Z, after the build of 2026-10-05 09:49Z, v0.77.0, 34 restarts, ledger-audit: ok: no unexplained adjustment, no leg unread twice; no state file (onchain-credit-check-ingester-freshness.state.json absent) and no alert file, no message sent. Step 2: no could not value readings this look line. On today's data (withheld-readings=0 on the one holding wallet) no served figure moved.

Rollback: revert the release commit on main; the deploy restarts the app, the ingester and the worker on the old code. The page then sums an unvalued reading's book without it again (the book less that holding, $0 if it was the only one), and the hourly arm pages every failed look at once with its [partial] line and the generic message. Nothing to undo in the database (no migration, no row written). The state file is the old code's to ignore; delete it if wanted: rm -f /tmp/onchain-credit-cron/onchain-credit-check-ingester-freshness.state.json. If LEDGER_AUDIT_SOURCE_PAGE_AFTER was set, it is inert under the old code.

The instrument master's exit terms, complete (migration 130, #1010): prod steps, in order ​

  • belongs to: the instrument-master terms PR (#1010, branch feat/1010-instrument-master-terms), migration 130
  • executed: 2026-10-08
  • run record: (23:01:05 UTC, by the standing runner after the v0.84.0 deploy 736a6299; migrate creddit: 2 applied, 130 total on disk). First query: 0|9|3. Second query: apyUSD|instant|queued|{ethereum}|, cbETH|offchain|offchain|{}|, PST|bridged|bridged|{solana}|, sUSDai|bridged|bridged|{arbitrum}|, sUSDat|instant|queued|{ethereum}| (ordered by symbol).

What it changes for a user, in one line: nothing visible. Every active registry row gains its exit terms and the networks it is redeemable on; no valuation, pricing category or feed moves. Eleven curator-vault and lending-style fund shares (the Morpho, Euler and Yearn vaults, iETHv2, fLiteUSD) are declared instant with the erc4626 capacity reader, so from the deploy the six-hourly capacity pass reads them too (fund shares are never category-tested, so those readings decide nothing), and any carry using one as collateral would read "The primary mint and redemption route anchors this asset's price." instead of "No secondary-market quote supported for this collateral." (the live carry list was not checked for such a carry).

  1. The deploy (merge staging into main). The new release does not read the two new columns (redeem_networks, exit_queue), so it runs identically before and after step 2; its loader does admit the two new terms, offchain and bridged.

  2. Migration 130, after the deploy, by the standing runner (no destructive tag). Not before: the previous release bounds the terms columns against its five-term vocabulary and would read PST, sUSDai and cbETH back with NULL terms, which drops them from the six-hourly category test until it is replaced. It also has no fund-share flag: it keeps the 18 fund shares out of the category test only because their terms are NULL, so against a migrated database it would test them (see Rollback).

    bash
    cd /opt/onchain-credit && scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)"
    sudo -u postgres psql -d creddit -At -c "SELECT count(*) FILTER (WHERE mint_terms IS NULL OR redeem_terms IS NULL OR redeem_networks IS NULL OR terms_verified IS NULL) AS unclassified, count(*) FILTER (WHERE exit_queue IS NOT NULL) AS modelled, count(*) FILTER (WHERE redeem_terms = 'bridged') AS bridged FROM onchain_credit.portfolio_tokens WHERE chain_id = 1 AND status = 'active'"
    sudo -u postgres psql -d creddit -At -c "SELECT symbol, mint_terms, redeem_terms, redeem_networks, exit_queue FROM onchain_credit.portfolio_tokens WHERE chain_id = 1 AND address IN ('0xd166337499e176bbc38a1fbd113ab144e5bd2df7', '0x38eeb52f0771140d10c4e9a9a72349a329fe8a6a', '0x22ae3d9a738471f405169af055d31c687087d4c7', '0x0b2b2b2076d95dda7817e785989fe353fe955ef9', '0xbe9895146f7af43049ca1c1ae358b0541ea49704') ORDER BY symbol COLLATE \"C\""

    Expect 0|9|3 (no unclassified active row, nine modelled queues, three bridged copies) on a database holding only the registry's own rows; a row an operator or the weekly sync added outside the registry counts as unclassified, and is the next listing decision rather than a failure of this step. The second query (from the registry's 130 list):

    text
    PST|bridged|bridged|{solana}|
    apyUSD|instant|queued|{ethereum}|
    cbETH|offchain|offchain|{}|
    sUSDai|bridged|bridged|{arbitrum}|
    sUSDat|instant|queued|{ethereum}|
  3. Record the run here: the date in executed: and both queries' output.

Rollback. The file only widens CHECKs, adds two columns nothing reads yet, and writes route columns, so it is never reverted. A code rollback to the previous release with 130 applied has two effects. (a) It reads offchain / bridged as NULL, so PST, sUSDai and cbETH leave the six-hourly category test. (b) It runs the category test on the 18 fund shares, which now carry terms: the weekly DEX-market measurement covers them and the six-hourly verdict can write loopable / loopable_verified for them (for example false once the market limb reads no market), which this release never clears because it never tests a fund share. No category moves (their declared category is redemption, so the candidate agrees) and no page reads loopable. Remedy: re-deploy this release, then clear the flag on the fund-share rows if any were written:

bash
sudo -u postgres psql -d creddit -c "UPDATE onchain_credit.portfolio_tokens SET loopable = NULL, loopable_verified = NULL WHERE chain_id = 1 AND address IN ('0xa0d3707c569ff8c87fa923d3823ec5d81c98be78','0x3a43aec53490cb9fa922847385d82fe25d0e9de7','0x0000000f2eb9f69274678c76222b35eec7588a65','0x273da948aca9261043fbdb2a857bc255ecc29012','0x696d02db93291651ed510704c9b286841d506987','0xb9e806e8f2d94c015ffefa90cd24ecce18f1663c','0xf0bb20865277abd641a307ece5ee04e79073416c','0xd11c452fc99cf405034ee446803b6f6c1f6d5ed8','0xbbfc8683c8fe8cf73777fede7ab9574935fea0a4','0x4ce1ac8f43e0e5bd7a346a98af777bf8fbea1981','0xbeef01735c132ada46aa9aa4c54623caa92a64cb','0xdd0f28e19c1780eb6396170735d45153d261490d','0x8eb67a509616cd6a7c1b3c8c21d48ff57df3d458','0xd63070114470f685b75b74d60eec7c1113d33a3d','0xc582f04d8a82795aa2ff9c8bb4c1c889fe7b754e','0x8cb3649114051ca5119141a34c200d65dc0faa73','0x797dd80692c3b2dadabce8e30c07fde5307d48a9','0xe0a80d35bb6618cba260120b279d357978c42bce') AND loopable IS NOT NULL"

The instrument kind of every registry row (migration 131): prod steps ​

  • belongs to: the instrument-kind PR (branch feat/instrument-kind), migration 131
  • executed: 2026-10-08
  • run record: (23:01:06 UTC, by the standing runner right after 130, deploy 736a6299 / v0.84.0). Query output, exactly as expected: credit_rwa|15, issuer_savings_rate|6, lending_vault_share|8, managed_strategy|11, plain_token|20, protocol_deposit_receipt|1, stablecoin|24, staking|9; no (none) line.

What it changes for a user, in one line: nothing. Every registry row gains one declared instrument kind (what backs it and how it earns); nothing reads the column this release, and no term, pricing category, valuation or feed moves.

  1. The deploy (merge staging into main). Order does not matter: neither this release nor the previous one reads instrument_kind (the loader starts reading it the release after, the schema-first rule), so the file can be applied before or after the deploy. Apply 130 first if it is still pending (#instrument-terms); the runner applies files in order anyway.

  2. Migration 131, by the standing runner (no destructive tag):

    bash
    cd /opt/onchain-credit && scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)"
    sudo -u postgres psql -d creddit -At -c "SELECT coalesce(instrument_kind, '(none)'), count(*) FROM onchain_credit.portfolio_tokens WHERE chain_id = 1 AND status = 'active' GROUP BY 1 ORDER BY coalesce(instrument_kind, '(none)') COLLATE \"C\""

    Expect, on a database holding only the registry's own rows (94 active):

    text
    credit_rwa|15
    issuer_savings_rate|6
    lending_vault_share|8
    managed_strategy|11
    plain_token|20
    protocol_deposit_receipt|1
    stablecoin|24
    staking|9

    A (none) line counts rows an operator or the weekly sync added outside the registry: each is the next listing decision (declare its kind in the registry), not a failure of this step (the fixture database reads (none)|4 for its four synthetic rows). The ORDER BY names the expression: ORDER BY 1 COLLATE "C" is read as a constant, not a column position, and errors.

  3. Record the run here: the date in executed: and the query's output.

Rollback. The file adds one column nothing reads yet and writes it, so it is never reverted, and a code rollback with 131 applied changes nothing (the previous release does not select the column). Dropping the column is never needed; if it ever were, it would be a destructive file of its own.

iUSD and reUSD leave the queued-redemption series (migration 132, #1087): prod steps ​

  • belongs to: the #1087 series-hygiene PR (branch oc-1087-hygiene), migration 132
  • executed: 2026-10-09
  • run record: (v0.85.0, release PR #1097, merge b520bbdb, deploy run 37970504638 green; the app restarted on 0.85.0 at 18:03:42Z; migrate.sh at 18:04Z applied 132 to 136, five files). Step 2's query at 18:05Z read exactly iUSD|instant|instant|none|2026-10-09|{ethereum}| and reUSD|gated|gated|none|2026-10-09|{ethereum}|.

What it changes for a user, in one line: nothing visible. Two registry rows have their exit terms re-read (iUSD redeems instant, reUSD is gated both ways); no valuation, pricing category, feed or capacity reading moves, and the terms are not shown on any page.

  1. The deploy (merge staging into main). Order does not matter: every term the file writes is in the vocabulary this release and the previous one both read, and neither row moves category under either.

  2. Migration 132, by the standing runner (no runner tag):

    bash
    cd /opt/onchain-credit && scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)"
    sudo -u postgres psql -d creddit -At -c "SELECT symbol, mint_terms, redeem_terms, capacity_reader, terms_verified, redeem_networks, exit_queue FROM onchain_credit.portfolio_tokens WHERE chain_id = 1 AND address IN ('0x48f9e38f3070ad8945dfeae3fa70987722e3d89c', '0x5086bf358635b81d8c47c66d1c8b9e567db70c72') ORDER BY symbol COLLATE \"C\""

    Expect:

    text
    iUSD|instant|instant|none|2026-10-09|{ethereum}|
    reUSD|gated|gated|none|2026-10-09|{ethereum}|
  3. Record the run here: the date in executed: and the query's output.

Rollback. The file writes two rows' route columns with values both releases read, so it is never reverted, and a code rollback with 132 applied changes nothing on a page.

Renzo's ezETH withdrawal, held in settlement (migration 133, #1087): prod steps, in order ​

  • belongs to: the escrow class renzo-ezeth-withdraw-queue (family renzo-queue; branch oc-1087-ezeth), migration 133 (ezETH's registry row names the class)
  • executed: 2026-10-09
  • run record: (v0.85.0, release PR #1097, merge b520bbdb, deploy run 37970504638 green; the app restarted on 0.85.0 at 18:03:42Z; migrate.sh at 18:04Z applied 132 to 136, five files). Done: step 2 (ezETH|queued|{ethereum}|renzo-ezeth-withdraw-queue); step 3 at 18:10Z, exit 0, 9 class(es), 33 assertion(s) (the release also carries wBETH), the six Renzo lines exactly as above, no moved line, OK — 33 assertion(s) match the chain; step 4, TO 26156494, dry run plan [22527558,26156494] · 73/73 window(s), 7 certificate key(s), the sweep 18:10:59Z to 18:15:24Z, exit 0, range done [22527558,26156494] · 13698 new row(s): the queue's 0x59557aa2… 6997 rows from block 22528617 and 0x600d0955… 6651 from 22529488 (13,644 together to block 26,153,808, as expected; 13,279 inside the band range). Steps 5 and 6 ran once for both classes, as the wBETH entry's record states: the band dry run measured 313,819 against the expected 313,813 (6 Maple logs, explained there), Fred confirmed it, the band was recorded at 19:49Z and the completion run stamped 7 coverage row(s) stamped live from 22527558 at 20:02Z, verify PASS. Step 7's wallet list (read-only): 0 rows at 18:31Z and again at 20:03Z, after step 6, so nothing to re-derive and step 8 had no wallet. The shared-code regression check (read-only, 18:32Z): both prod test wallets have their derive cursor (26150760 / 26150765, settled-through 26156578 at 18:28Z, after the deploy), 0 held-back rows, 31 / 213 escrow rows.

What it changes for a user, in one line: a wallet that asks Renzo for its ezETH back keeps the value on its page through the 14-day wait, listed as ezETH marked In settlement and worth what the claim will pay, and its Activity reads one redemption ("Redemption requested", then "Redemption paid") instead of a withdrawal and, two weeks later, a fresh deposit.

What it does, and what it leaves.

  • Code, plus one additive registry update. The escrow class registry gains its eighth class; the escrow stream gains one filter (the queue's two request layouts and its claim, three topics) and one certificate key (the queue, 0x5efc9d10e42fb517456f4ac41eb5e2ebe42c8918); the snapshot pass reads every wallet's open Renzo requests; the derivation writes each redemption's movements. Minting ezETH through Renzo's RestakeManager (ether or stETH in) is booked as an exchange of holdings instead of a withdrawal and a deposit.
  • The live ingester scans the new filter from its own cursor as soon as it restarts on the release. The stream's HISTORY below that holds none of Renzo's logs until step 4 sweeps it, and the new key has no certificate row until step 6 earns it.
  • Between the deploy and step 6 the change fails closed, exactly as the f(x) release did (its entry): a wallet whose reading holds an open Renzo request, or whose ledger holds a Renzo movement the live ingester saw after the deploy, requires a certificate nobody has written yet and withholds (W7 uncertified-scope) until step 6, then clears on its own. The reconciler can page for those wallets ([fail] ledger-reconcile excluded=…) until then: run steps 3 to 6 straight after the deploy.
  • A redemption that straddles the deploy reads half old, half new until step 7: its request derived by the previous release (the ezETH sent to the queue as money withdrawn) and its claim by this one. Step 7 takes its wallet list after step 6 for that reason.

Prod, in order. Steps 4 to 8 write prod and need the owner's go.

  1. Plan the window, before the deploy. Steps 3 to 6 run straight after it, attended. Take no wallet list now (step 7).

  2. The deploy (the release merge), and migration 133: one additive UPDATE of ezETH's registry row (exit_queue = 'renzo-ezeth-withdraw-queue'), safe before or after the deploy (nothing reads the column at run time). Applied by the standing runner after the deploy; check it, read-only:

    sql
    SELECT symbol, redeem_terms, redeem_networks, exit_queue
      FROM onchain_credit.portfolio_tokens
     WHERE chain_id = 1 AND address = '0xbf5495efe5db9ce00f80364c8b423567e58d2110';
    -- ezETH|queued|{ethereum}|renzo-ezeth-withdraw-queue

    Migration 132 (iUSD and reUSD) amends other rows; the two files touch disjoint rows and apply in either order.

  3. The registry check, read-only:

    bash
    cd /opt/onchain-credit && ETHEREUM_RPC_URL="$(grep ^ETHEREUM_RPC_URL= .env.local | cut -d= -f2-)" \
      npm run verify:escrow-registry

    Exit 0, 8 class(es), 28 assertion(s), and the six new lines read (mainnet, read from the branch on 2026-10-09: all 28 assertions matched):

    text
    ok   renzo-ezeth-withdraw-queue depositQueue()         0xf2f305d14dcd8aaef887e0428b3c9534795d0d60
    ok   renzo-ezeth-withdraw-queue withdrawQueue()        0x5efc9d10e42fb517456f4ac41eb5e2ebe42c8918
    ok   renzo-ezeth-withdraw-queue ezETH()                0xbf5495efe5db9ce00f80364c8b423567e58d2110
    ok   renzo-ezeth-withdraw-queue renzoOracle()          0x5a12796f7e7ebbbc8a402667d266d2e65a814042
    ok   renzo-ezeth-withdraw-queue getProxyImplementation(address)[0x5efc9d10e42fb517456f4ac41eb5e2ebe42c8918] 0xf821a5cff2cdd014c6e6bbb8e05b81c3d7e98003
    ok   renzo-ezeth-withdraw-queue coolDownPeriod()       1209600

    getProxyImplementation and coolDownPeriod are report-only: a changed value prints as moved, adds a reported, not held line and still exits 0. A moved implementation means Renzo upgraded the queue (eleven implementations in sixteen months; one changed the request event, three what a stETH claim pays): read the new implementation's events, withdraw, claim and calculateAmountToRedeem before going on, and re-pin it in the registry with that reading. A drift on any of the four hard lines (a redeployed queue, a new oracle) holds the escrow cursor: stop before step 4 and find out why.

  4. GATED: sweep the escrow stream from the floor to its live cursor, so the new filter's history is ingested (attended; idempotent upserts, archive RPC; the other filters re-read stored rows):

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    TO=$(psql "$DATABASE_URL" -tAc "SELECT last_scanned_block FROM onchain_credit.chain_scan_cursors WHERE chain_id = 1 AND scope = 'ledger:escrow'")
    npx tsx scripts/backfill-event-ledger.ts --stream escrow --from 22527558 --to "$TO" --dry-run
    npx tsx scripts/backfill-event-ledger.ts --stream escrow --from 22527558 --to "$TO"

    Check, read-only: SELECT topic0, count(*), min(block_number), max(block_number) FROM onchain_credit.raw_events WHERE chain_id = 1 AND stream = 'escrow' AND address = '0x5efc9d10e42fb517456f4ac41eb5e2ebe42c8918' GROUP BY 1 returns two rows, 0x600d0955… (requests) and 0x59557aa2… (claims), from near the floor; 13,644 together to block 26,153,808 (the first layout, 0x841b0903…, ended at block 20,262,794, below the floor, and returns no row).

  5. GATED: re-measure the stream's history band over the seven filters, from the second provider (the frozen 300,500 counts six):

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    LEDGER_VERIFY_RPC_URL=<second provider> \
      npx tsx scripts/record-ledger-backfill-band.ts --stream escrow --to 25828233 \
        --note "<date> Renzo's ezETH queue joins the escrow stream" --window 5000 --dry-run
    # then the same with --confirm in place of --dry-run

    Expect 300,500 plus Renzo's 13,279 over [22,527,558, 25,828,233]: 313,779.

  6. GATED: the completion run, which judges the corpus against step 5's band and promotes the certificate, the new key included:

    bash
    npx tsx scripts/backfill-event-ledger.ts --stream escrow
    npx tsx scripts/backfill-event-ledger.ts --verify --stream escrow   # read-only

    Expect 6 coverage row(s) stamped live from 22527558 and a verify PASS; event_coverage lists six escrow rows, the queue's among them, all live from 22527558. A refusal publishes nothing and names its reason; do not answer it by re-running.

  7. GATED: after step 6, take the wallet list (read-only), then re-derive those wallets from their floor, and only those. The list is every enrolled wallet that ever moved ezETH (every request sends ezETH to the queue). What a re-derive recovers, and what it cannot:

    • A request made inside the wallet's window: recovered. Its request event is in the swept stream, so the re-derive books the request and its claim as one redemption (no withdrawal, no deposit).
    • A request made BEFORE the window and claimed inside it: NOT recovered by a re-derive. The claim log names no owner, so the derivation can only own it through a ticket the wallet already held at the window's opening, and that comes from the STORED opening reading, which the previous release's reader took without this class. The claim's ether then still books as a deposit and the ezETH it came from as having left before the window. Recovering it needs that opening reading re-read with this release's escrow reader for the listed wallets. That repair was not built: the ETHx release decided against it on measurement (no enrolled wallet held an open request of any of the three new queues at its window start on 2026-10-09; see its entry), and each later asset release checks again before its deploy. Prod has 0 ezETH wallets on 2026-10-09, so nothing here is affected today.

    The wallet-token stream stores every transfer touching an enrolled wallet:

    sql
    -- read-only: the wallet list for steps 7 and 8
    WITH w AS (SELECT uid, '0x000000000000000000000000' || substr(uid, 3) AS t FROM onchain_credit.accounts)
    SELECT w.uid
      FROM w
     WHERE EXISTS (SELECT 1 FROM onchain_credit.raw_events e
                    WHERE e.chain_id = 1 AND e.stream = 'wallet-token'
                      AND e.address = '0xbf5495efe5db9ce00f80364c8b423567e58d2110'
                      AND e.topic0 = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
                      AND (e.topic1 = w.t OR e.topic2 = w.t))
     ORDER BY 1;

    Zero rows means steps 7 and 8 have nothing to do. Otherwise queue one whole-window rederive per listed wallet with the runbook's insert (its own history floor to the chain head) and read it done from portfolio_derive_jobs. Never before step 6: a re-derived wallet with a Renzo movement then requires the missing certificate and withholds.

  8. Check, read-only, per re-derived wallet:

    sql
    SELECT block_number, venue, position_key, kind, amount_raw, consideration_raw, to_balance, link_id
      FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND wallet = '<wallet>' AND link_kind = 'escrow'
       AND (position_key LIKE 'escrow:renzo-ezeth-withdraw-queue:%' OR meta->>'escrowClass' = 'renzo-ezeth-withdraw-queue')
     ORDER BY block_number, log_index, seq;

    Every request is one link_id (esc:1:0x5efc…8918:<request id>) holding an internal_out on wallet:token:0xbf54…2110 (its consideration_raw the ticket's ether value) and an internal_in on escrow:renzo-ezeth-withdraw-queue:<id>, and at its claim an internal_out on the ticket (its to_balance 0) beside the ether (or stETH) internal_in. No transfer_out of ezETH to the queue and no transfer_in of the claim's ether remain; a ticket paid in wBETH closes into a wBETH internal_in once wBETH is listed (its entry; before that, a transfer_out with meta.paidIn wBETH). Zero held-back rows (meta->>'withheld') for the class, the reconciler's line for the wallet (npx tsx scripts/ops/reconcile-ledger.ts --wallet <wallet>) clean, and on /portfolio an open request reads as an In settlement ezETH row with a value and a Dislocation P&L figure. Then the issue's shared-code regression check: the two prod test wallets (0xdd647ce1…c737, 0xd1a557fe…6e09) still build their history completely (derive cursor present, zero held-back rows, their In settlement rows valued).

  9. Record executed: with the date, step 3's output, step 6's coverage lines and step 8's rows.

Staging. Steps 3 and 8's queries are read-only and safe there; the nightly reseed restores prod's raw_events and event_coverage, so a staging sweep is undone by the next reseed and proves nothing about prod (staging's data is a reseed).

Rollback. A code rollback does not roll back the database. The previous release reads no Renzo leg, so a wallet holding the class's rows is refused by its escrow universe until it is re-derived under the previous code (which books the ezETH sent and the ether received as transfers again). The ingested Renzo logs, the queue's certificate row and migration 133's exit_queue value are inert under the previous code.

Binance wBETH, listed with its unwrap queue held in settlement (migration 136, #1087): prod steps, in order ​

  • belongs to: wBETH's registry row and the escrow class binance-wbeth-unwrap-queue (family binance-queue; branch oc-1087-wbeth), migration 136
  • executed: 2026-10-09
  • run record: (v0.85.0, release PR #1097, merge b520bbdb, deploy run 37970504638 green; the app restarted on 0.85.0 at 18:03:42Z; migrate.sh at 18:04Z applied 132 to 136, five files). Step 1 ran AFTER migration 136, at 18:05Z (the promotion review's S1: before 136 the plan cannot see a wBETH reading): [restate] nothing to restate: every stored reading agrees with the registry's book (11 accounts). Step 2's query read exactly the expected row. Step 3: backfill-wbeth.ts 18:06Z to 18:29Z, done: 5054 rows, 5050 with apy, avg apy 3.01%, price 1.000000 → 1.108096 · 5054 ok / 0 fail; backfill-token-supply.ts [backfill-supply/wBETH] done: ok=5054 failed=0 (earnETH 1031 and sUSDai 1464 failures, the same as its 2026-10-02 run); backfill-apy-30d.ts done: 232044 rows updated; the series 2023-04-25 12:00 to 2026-10-09 18:00, 5054 rows, 4934 with apy_30d, newest share_rate 1.108096042353; refresh-assets.ts by hand 18:37Z to 18:39Z (14 ok, 1 failed: the standing rUSD quiet-feed alert, also on the 18:00 tick), the assets row wBETH|Wrapped Binance Beacon ETH|Binance|8762972769.73|0.02255. Step 4: exit 0, 9 class(es), 33 assertion(s), the five lines exactly as above, no moved line. Step 5 (the one sweep for both classes, Renzo's record): the queue's 0x96d07fd2… 25 requests (24 to block 26,154,529 plus one at 26,154,885) and 0x11636acb… 19 claims; 34 inside the band range. Step 6: the dry run from the second provider (https://gateway.tenderly.co/public/mainnet, 18:15:53Z to 18:28:07Z) measured 313819 claimed row(s) (313819 raw log(s), 5288 chunk(s)) over [22527558,25828233]; the stored corpus over the same range is also 313,819. The operator stopped there because the figure was outside the expected 313,813. Fred confirmed the measured figure, and the coordinator ran the rest at 19:49Z: record-ledger-backfill-band.ts --stream escrow --to 25828233 --window 5000 --confirm, recorded escrow=313819 over [22527558,25828233] (superseding 300500; independence established against the sweep's Alchemy receipts, measured via Tenderly). 313,819 = the expected 313,813 plus 6 Maple syrupUSDC withdrawal-manager logs of 2026-02-03 (ManualSharesIncreased 3, ManualSharesDecreased 3, blocks 24,376,315 to 24,376,417, owner 0x02b6…a2c4, not an enrolled wallet): those two event types joined the escrow filter with #1029 (v0.80.0), after the 300,500 band of 2026-10-04, and this sweep was the first to fill their history. The completion run at 20:02Z (backfill-event-ledger.ts --stream escrow): condition 1 313819 vs [313819,313819] pass, condition 3's digest of [25777558,25827557] pass, 7 coverage row(s) stamped live from 22527558, complete [22527558,25828233] · 0 new row(s), exit 0; --verify --stream escrow at 20:02Z: verify PASS · run 928b443cb7fb, every stream passing all four conditions, exit 0. event_coverage (read 2026-10-09 after the run): seven escrow addresses live from 22527558, the Renzo queue 0x5efc…8918 and the Binance queue 0x7997…0196 among them, beside the stream's * marker, all stamped 20:02:19Z. Note: the Maple syrupUSDC queue's certificate read complete from v0.80.0 until this sweep while those 6 logs were missing; no tracked wallet was affected and no repair is owed. Step 8's wallet list (read-only): 0 rows at 18:31Z and again at 20:03Z, after step 7, so step 9 had no wallet; the regression check at 20:03Z still reads 0 held-back rows on both prod test wallets.

What it changes for a user, in one line: a wallet holding wBETH sees it valued in the ETH view under Variable rate assets at Binance's posted rate (with an asset profile), and a wallet that asks Binance for its ether back keeps the value on its page through the wait, listed as wBETH marked In settlement and worth exactly the ether the claim will pay, its Activity reading "Redemption requested" then "Redemption paid" instead of a withdrawal and a deposit weeks later. A Renzo claim paid in wBETH now arrives as a wBETH holding (none since September 2024).

What it does, and what it leaves.

  • Code, plus one additive migration (136: a new registry row and its route columns). The escrow class registry gains its ninth class; the escrow stream gains one filter (the queue's request and claim, two topics) and one certificate key (the queue, 0x79973d557cd9dd87eb61e250cc2572c990e20196); the snapshot pass reads every wallet's open wBETH requests; the derivation writes each redemption's movements, and minting wBETH with ether is booked as an exchange of holdings. The registry check gains two IMPLEMENTATION pins (each proxy's public implementation()), report-only like Renzo's: an upgrade of the wBETH token or the queue prints moved for a re-reading of the new code and holds nothing.
  • wBETH buys no price bars (redemption-priced, no feed); its rate series is step 3's backfill.
  • Between the deploy and step 7 the queue fails closed, as the Renzo release did (its entry): a wallet whose reading holds an open wBETH request, or whose ledger holds a movement of this class the live ingester saw after the deploy, withholds (W7 uncertified-scope) until step 7 earns the certificate, then clears on its own. Run steps 4 to 7 straight after the deploy.
  • Existing wallets' wBETH history re-prices by itself (B.2a): readings stored while wBETH was outside coverage carry book EXCLUDED, and the ledger worker restates them into the ETH book from its first turn after the deploy. Step 1 names them first.

Prod, in order. Steps 3 and 5 to 9 write prod and need the owner's go.

  1. Before the deploy, read-only: does any enrolled wallet hold a wBETH request at its window start? For every account, the unwrap queue's list of the wallet's unclaimed requests at its history floor block (getUserWithdrawRequests(owner); the second word of its answer is the count):

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    PGOPTIONS='-c default_transaction_read_only=on' psql "$DATABASE_URL" -tA -F' ' \
      -c "SELECT uid, history_floor_block FROM onchain_credit.accounts WHERE history_floor_block IS NOT NULL ORDER BY 1" |
    while read -r w b; do
      r=$(curl -s -X POST -H 'content-type: application/json' "$ETHEREUM_ARCHIVE_RPC_URL" -d \
        "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"eth_call\",\"params\":[{\"to\":\"0x79973d557cd9dd87eb61e250cc2572c990e20196\",\"data\":\"0x781364bd000000000000000000000000${w:2}\"},\"$(printf '0x%x' "$b")\"]}" |
        sed -nE 's/.*"result":"0x[0-9a-f]{64}([0-9a-f]{64}).*/\1/p')
      if [[ "$r" =~ ^[0-9a-f]{64}$ ]]; then echo "$w floor=$b open_requests=$((16#${r: -8}))"; else echo "$w floor=$b read_failed"; fi
    done

    Every line reads open_requests=0 (all 11 on 2026-10-09). A read_failed line: run it again until every wallet answers. A non-zero line: stop, do not deploy, and bring the wallet to Fred: its claim would book a gain that never happened (above). The remedies are the ticket guard for this class (a code change landed before the release) or that wallet's opening reading re-read.

  2. Before the deploy, read-only: the plan. The coverage restatement plan names every wallet and reading the release re-prices, and the wallet list of step 8 is taken AFTER step 7 (a request that straddles the deploy reads half old, half new until it is re-derived):

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    PGOPTIONS='-c default_transaction_read_only=on' npx tsx scripts/ops/restate-covered-readings.ts --plan --db-url "$DATABASE_URL"
  3. The deploy, then migration 136 at once, before the next six-hourly portfolio tick (by the standing runner; no destructive tag). Check, read-only:

    sql
    SELECT symbol, status, wallet_tracked, book, class, valuation, feed, underlying_address, rate_kind, rate_getter,
           liquidity, mint_terms, redeem_terms, capacity_reader, redeem_networks, exit_queue, instrument_kind, profile_ticker, issuer
      FROM onchain_credit.portfolio_tokens
     WHERE chain_id = 1 AND address = '0xa2e3356610840701bdf5611a53974510ae27e2e1';
    -- wBETH|active|t|ETH|variable_rate|composed||0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2|getter|{"kind": "cbeth_exchange_rate", "divisorPow10": 18}|primary_buffer|instant|queued|none|{ethereum}|binance-wbeth-unwrap-queue|staking|wBETH|Binance

    Migration 133 (Renzo) touches another row; the two apply in either order.

  4. GATED: wBETH's rate history, from its first mint, before the first tick reads it (the profile's 30-day APY and returns come from the series, and the series is the getter's fallback):

    bash
    /opt/onchain-credit/scripts/run-cron.sh backfill-wbeth.ts         # ~5,100 windows, 2 archive reads each
    /opt/onchain-credit/scripts/run-cron.sh backfill-token-supply.ts  # fills NULL total_supply, every token
    /opt/onchain-credit/scripts/run-cron.sh backfill-apy-30d.ts       # recomputes apy_30d, every token (pure DB)

    It opens at 2023-04-25 12:00 UTC (why); check, read-only: SELECT min(snapshot_ts), max(snapshot_ts), count(*), count(apy_30d) FROM onchain_credit.token_yield_apy WHERE token_address = '0xa2e3356610840701bdf5611a53974510ae27e2e1': about four rows a day since, the newest share_rate near 1.108 (1.108096042353 at block 26,154,529). Then the first refresh-assets tick by hand (scripts/run-cron.sh refresh-assets.ts, never during the deploy): SELECT ticker, name, issuer, productive_usd, current_apy FROM onchain_credit.assets WHERE ticker = 'wBETH' returns one fresh row (about 3.18M wBETH on Ethereum at 1.108 ETH each).

  5. The registry check, read-only:

    bash
    cd /opt/onchain-credit && ETHEREUM_RPC_URL="$(grep ^ETHEREUM_RPC_URL= .env.local | cut -d= -f2-)" \
      npm run verify:escrow-registry

    Exit 0, 9 class(es), 33 assertion(s), and the five new lines read (mainnet, from the branch on 2026-10-09):

    text
    ok   binance-wbeth-unwrap-queue _UNWRAP_ETH_ADDRESS()  0x79973d557cd9dd87eb61e250cc2572c990e20196
    ok   binance-wbeth-unwrap-queue WBETH_TOKEN_ADDRESS()  0xa2e3356610840701bdf5611a53974510ae27e2e1
    ok   binance-wbeth-unwrap-queue implementation()       0x9e021c9607bd3adb7424d3b25a2d35763ff180bb
    ok   binance-wbeth-unwrap-queue implementation()       0x542059d658624df6452b22b10302a15a6ab59f10
    ok   binance-wbeth-unwrap-queue lockTime()             3456000

    lockTime and the two implementations are report-only (a changed wait or an upgrade prints moved, exit 0; an upgrade is a finding to read before the next release). A drift on either address (a redeployed queue) holds the escrow cursor: stop before step 5.

  6. GATED: sweep the escrow stream from the floor to its live cursor (attended; idempotent; the other filters re-read stored rows):

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    TO=$(psql "$DATABASE_URL" -tAc "SELECT last_scanned_block FROM onchain_credit.chain_scan_cursors WHERE chain_id = 1 AND scope = 'ledger:escrow'")
    npx tsx scripts/backfill-event-ledger.ts --stream escrow --from 22527558 --to "$TO" --dry-run
    npx tsx scripts/backfill-event-ledger.ts --stream escrow --from 22527558 --to "$TO"

    Check, read-only: SELECT topic0, count(*) FROM onchain_credit.raw_events WHERE chain_id = 1 AND stream = 'escrow' AND address = '0x79973d557cd9dd87eb61e250cc2572c990e20196' GROUP BY 1 returns 0x96d07fd2… (requests, 24 to block 26,154,529) and 0x11636acb… (claims, 19).

  7. GATED: re-measure the stream's history band over the eight filters, from the second provider:

    bash
    LEDGER_VERIFY_RPC_URL=<second provider> \
      npx tsx scripts/record-ledger-backfill-band.ts --stream escrow --to 25828233 \
        --note "<date> Binance's wBETH unwrap queue joins the escrow stream" --window 5000 --dry-run
    # then the same with --confirm in place of --dry-run

    Expect the Renzo release's 313,779 plus Binance's 34 over [22,527,558, 25,828,233]: 313,813 (in a release that carries both, one re-measure after both sweeps).

  8. GATED: the completion run, which judges the corpus against step 6's band and promotes the certificate, the new key included:

    bash
    npx tsx scripts/backfill-event-ledger.ts --stream escrow
    npx tsx scripts/backfill-event-ledger.ts --verify --stream escrow   # read-only

    Expect 7 coverage row(s) stamped live from 22527558 and a verify PASS.

  9. GATED: after step 7, take the wallet list (read-only), then re-derive those wallets from their floor, and only those: every enrolled wallet that ever moved wBETH (every request burns it), and every wallet with a Renzo request that named wBETH:

    sql
    -- read-only: the wallet list for steps 8 and 9
    WITH w AS (SELECT uid, '0x000000000000000000000000' || substr(uid, 3) AS t FROM onchain_credit.accounts)
    SELECT w.uid
      FROM w
     WHERE EXISTS (SELECT 1 FROM onchain_credit.raw_events e
                    WHERE e.chain_id = 1 AND e.stream = 'wallet-token'
                      AND e.address = '0xa2e3356610840701bdf5611a53974510ae27e2e1'
                      AND e.topic0 = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
                      AND (e.topic1 = w.t OR e.topic2 = w.t))
     ORDER BY 1;

    Zero rows means steps 8 and 9 have nothing to do (2026-10-09: neither prod test wallet holds wBETH). Otherwise queue one whole-window rederive per listed wallet with the runbook's insert and read it done from portfolio_derive_jobs. A request opened before a wallet's window and claimed inside it is NOT safe here (what the code does today, measured on the ETHx release's engine probe): Binance's claim log names its owner, so the derivation closes the ticket even when no reading ever held it. The ether then arrives as an exchange rather than as money added, and the ticket's whole payout is booked as a gain on the position in settlement, on both the MTM PnL and the Accrual only PnL lines, a gain that never happened. A wallet whose window-opening reading was taken by this release's reader is fine (the ticket is held from the opening); a wallet enrolled before this release is not. Step 0 below is the control: no enrolled wallet may hold an open wBETH request at its window start when this release deploys. (Stader's class closes only a ticket the books hold, #stader-ethx-queue-release; extending that guard to this class is a separate change, not made yet.)

  10. Check, read-only, per re-derived wallet: portfolio_flow_events_v2 rows with link_kind = 'escrow' and position_key LIKE 'escrow:binance-wbeth-unwrap-queue:%' (or meta->>'escrowClass' that class): every request is one link_id (esc:1:0x7997…0196:<request id>) holding an internal_out of wBETH (its consideration_raw the ether owed) and an internal_in on the ticket, and at its claim an internal_out on the ticket (to_balance 0) beside the ether internal_in; zero held-back rows; the reconciler's line clean; on /portfolio an open request reads as an In settlement wBETH row with a value. Then the shared-code regression check of issue #1087 (the two prod test wallets build completely, their In settlement rows valued).

  11. Record executed: with the date, step 0's lines, steps 2 to 4's output, step 7's coverage lines and step 9's rows.

Staging. The read-only checks are safe there; a staging sweep is undone by the nightly reseed.

Rollback. A code rollback does not roll back the database. The previous release has no wBETH class, so a wallet holding its rows is refused by its escrow universe until re-derived under the previous code; it reads wBETH's database-only row through its registry overlay and values it with the getter it already has. The ingested logs, the certificate row and migration 136's row are inert under the previous code.

StakeWise's osETH exit queue, held in settlement (migration 144, #1087): prod steps, in order ​

  • belongs to: the escrow class stakewise-oseth-exit-queue (family stakewise-queue; branch oc-1087-oseth), migration 144 (osETH's registry row names the class)
  • executed: 2026-10-12
  • run record: (v0.87.0, release PR #1126, merge 1284e4c7 at 17:10:33Z on 2026-10-12, deploy run 38282474222 green 17:10:41Z to 17:11:55Z: app, ingester and worker restarted 17:11:53Z to 17:11:55Z, health 200, box on 0.87.0; 141 by hand at 17:10:13Z before the merge; one migrate.sh at 17:12:34Z to 17:12:41Z: 5 applied (140, 142, 143, 144 and #1124's 145), 144 total on disk; run as the combined pass.) Step 0 (17:09:56Z, read-only, run twice): 15 accounts, all answering, every one tickets_at_floor=0 tickets_now=0. Step 1: osETH|queued|{ethereum}|stakewise-oseth-exit-queue. Step 2: exit 0, 13 class(es), 61 assertion(s), the four lines ok exactly as above (no moved). Step 3 (the one sweep with Saturn's class, its record): the redeemer's requests 0x211091c5… 91 (the first at 25,067,970, the last at 26,089,388) and claims 0xeb3b05c0… 86 (the first at 26,034,764); 1 inside the band. Step 4: the shared band, recorded escrow=176760 over [24136053,25828233] (171,643 + 5,117). Step 5: 11 coverage row(s) stamped live from 24136053, the verify verify PASS · run c1e832d0591d (Saturn's record has the lines). Step 6: the list query returned 0 rows, so nothing was re-derived for this class and step 7 had no wallet; the two prod test wallets' regression check (Saturn's record) passed.

What it changes for a user, in one line: a wallet that asks StakeWise's exit queue to redeem its osETH keeps the value on its page through the wait, listed where the osETH sat as osETH marked In settlement in the ETH view, worth the osETH at osETH's rate (the part StakeWise has filled at the ether set aside for it); its Activity reads one redemption ("Redemption requested", then "Redemption paid", or "Redemption partly paid" where a claim paid only the filled part and the rest continues as a new request) instead of a withdrawal and, hours later, a fresh deposit. Buying osETH from the queue with ether (the redeemer's own swap) is booked as an exchange of holdings.

What it does, and what it leaves.

  • Code, plus one additive registry update. The escrow class registry gains its thirteenth class; the escrow stream gains one filter (the redeemer's ExitQueueEntered and ExitedAssetsClaimed, two topics) and one certificate key (the redeemer, 0xc43a7b16a7a167c0318390cba16787c11e9e1fd0); the snapshot pass reads every wallet's tickets from the candidates the redeemer's stored logs name (exitRequests under the wallet's key, the covering checkpoint, what a claim would pay now, and the rest at osETH's rate); the derivation writes each redemption's movements. The registry check gains one storage read (the redeemer's EIP-1967 slot, zero: it is not a proxy) beside its multicall.
  • No by-hand step before the merge. Migration 144 sets only exit_queue and restates redeem_networks on osETH's row; the registry the app loads at start, and the ingester and the ledger worker re-read every five minutes (loadTokenRegistryRows, src/lib/data/registry-load.ts), reads neither column (their values come from the code's own registry), and the class and its stream filter are code. The standing runner applies it after the deploy, with no restart, exactly as 140 was.
  • The redeemer was deployed at block 24,923,158 (2026-04-20), after the coverage floor, so the sweep from the floor is its whole history: no ticket can predate the stored logs, which is also what lets the snapshot pass name a wallet's tickets from those logs (the redeemer has no view that lists them).
  • This is not the main osETH exit. A staker who minted osETH against a StakeWise vault stake burns it against its own position and leaves through the vault's own queue in vault shares, which creddit does not track; only a bare osETH holder's exit, the redeemer, is modelled. Minting osETH against a vault stake is a loan on that stake and still arrives as money added.
  • Between the deploy and step 5 the change fails closed, exactly as the Stader, Apyx and Saturn releases did (Saturn's entry): a wallet whose reading holds an open ticket, or whose ledger holds a movement of this class the live ingester saw after the deploy, withholds (W7 uncertified-scope) until step 5 earns the certificate, then clears on its own. Run steps 2 to 5 straight after the deploy.
  • A redemption that straddles the deploy reads half old, half new until step 6: its request derived by the previous release (the osETH sent to the redeemer as money withdrawn) and its claim by this one, whose claim is then left as money added because the books never held the ticket. Step 6 takes its wallet list after step 5 for that reason.
  • What a re-derive recovers, and what it cannot. A request made inside the wallet's window is recovered: its request event is in the swept stream, so the re-derive books the request and its claim (or claims, for a ticket paid in parts) as one redemption. A ticket requested BEFORE the window and claimed inside it is closed only if a stored reading held it (the wallet's window-opening reading, or any reading the snapshot pass took while it was open). A reading taken before this release never holds a StakeWise ticket, so for a wallet enrolled before the release with such a ticket, the claim's ether stays money added (a deposit) and the osETH is the holding that left before the window, exactly as before the release; a rest that ticket's partial claim left is not held either. It is never closed from nothing: a ticket no reading valued would book its whole payout as a gain. Re-reading those wallets' opening readings is not built; step 0 lists them.
  • The queue has not moved since 2026-09-30. At block 26,175,689 four tickets worth about 31.6 ETH wait unfilled (the last checkpoint was at block 26,092,327), so a wallet's request may sit In settlement for a long time. Its settlement facts state no expected date while the queue has paid nothing for three typical waits (two days at least: the staleness guard of PR #1122's review, which applies to every queue), never the half-day the 30-day median of 2026-10-12 would otherwise promise.

In release v0.87.0 this entry ships with Saturn's, sUSDat's book, 142's, apxUSD and apyUSD's book and the coverage floor's last two steps, and they run as one order: the combined pass. Its order and numbers win where they differ from the steps below (one sweep, one band and one completion for both queues).

Prod, in order. Steps 3 to 7 write prod and need the owner's go.

  1. Before the deploy, read-only: which enrolled wallets held a StakeWise ticket at their window start? The redeemer lists no wallet's tickets, so the check names them from its own logs (each request's ticket, each partial claim's rest) and asks the redeemer for each one under the wallet's key, at the wallet's history floor and, for information, now. An account with no history floor of its own starts at the coverage floor (24,136,053), before the redeemer, so it held none at its start; it is still listed, with floor=none, for its tickets now:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    PGOPTIONS='-c default_transaction_read_only=on' psql "$DATABASE_URL" -tA -F' ' \
      -c "SELECT uid, coalesce(history_floor_block::text, 'none') FROM onchain_credit.accounts ORDER BY 1" \
      > /tmp/oseth-step0-wallets.txt
    npx tsx -e '
    const { readFileSync } = require("node:fs");
    const { encodeAbiParameters, keccak256 } = require("viem");
    const RPC = process.env.ETHEREUM_ARCHIVE_RPC_URL, R = "0xc43a7b16a7a167c0318390cba16787c11e9e1fd0", FROM = 24923158;
    const ENTERED = "0x211091c5bf013c1230f996c3bb2bc327e3de429a3d3c356dcea9a0c858bc407f";
    const CLAIMED = "0xeb3b05c070c24f667611fdb3ff75fe007d42401c573aed8d8faca95fd00ccb56";
    const rpc = async (method, params) => { const j = await (await fetch(RPC, { method: "POST", headers: { "content-type": "application/json" },
      body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }) })).json(); if (j.error) throw new Error(JSON.stringify(j.error)); return j.result; };
    const hex = (n) => "0x" + n.toString(16), pad = (w) => "0x" + w.slice(2).padStart(64, "0");
    (async () => {
      const head = Number(await rpc("eth_blockNumber", []));
      for (const line of readFileSync("/tmp/oseth-step0-wallets.txt", "utf8").trim().split("\n").filter(Boolean)) {
        const [w, floor] = line.split(" "); const b = floor === "none" ? 0 : Number(floor);
        try {
          const logs = [...await rpc("eth_getLogs", [{ address: R, fromBlock: hex(FROM), toBlock: hex(head), topics: [ENTERED, null, pad(w)] }]),
            ...await rpc("eth_getLogs", [{ address: R, fromBlock: hex(FROM), toBlock: hex(head), topics: [CLAIMED, pad(w)] }])];
          const tickets = [...new Set(logs.map((l) => BigInt("0x" + l.data.slice(l.topics[0] === ENTERED ? 2 : 66, l.topics[0] === ENTERED ? 66 : 130))).filter((t) => t > 0n))];
          const open = async (blockTag) => { let n = 0; for (const t of tickets) {
            const key = keccak256(encodeAbiParameters([{ type: "address" }, { type: "uint256" }], [w, t]));
            const r = await rpc("eth_call", [{ to: R, data: "0x7ce93e72" + key.slice(2) }, blockTag]); if (BigInt(r) > 0n) n++; } return n; };
          console.log(`${w} floor=${floor} tickets_at_floor=${b < FROM ? 0 : await open(hex(b))} tickets_now=${await open("latest")}`);
        } catch (e) { console.log(`${w} floor=${floor} read_failed`); }
      }
    })();'

    A read_failed line: run it again until every wallet answers. A non-zero tickets_at_floor does not stop the release (the guard above keeps the payout from booking as a gain); name the wallet in the run record: its ticket is the case a re-derive cannot recover, and its claim stays money added. A non-zero tickets_now is a wallet that will show an In settlement osETH row once step 6 has run.

  2. The deploy (the release merge), and migration 144: one additive UPDATE of osETH's registry row (exit_queue = 'stakewise-oseth-exit-queue', redeem_networks restated unchanged), applied by the standing runner after the deploy with no restart (above). Check it, read-only:

    sql
    SELECT symbol, redeem_terms, redeem_networks, exit_queue
      FROM onchain_credit.portfolio_tokens
     WHERE chain_id = 1 AND address = '0xf1c9acdc66974dfb6decb12aa385b9cd01190e38';
    -- osETH|queued|{ethereum}|stakewise-oseth-exit-queue

    Migrations 142 (staging's) and 143 (apxUSD and apyUSD's book) touch other rows; the files apply in any order.

  3. The registry check, read-only:

    bash
    cd /opt/onchain-credit && ETHEREUM_RPC_URL="$(grep ^ETHEREUM_RPC_URL= .env.local | cut -d= -f2-)" \
      npm run verify:escrow-registry

    Exit 0, 13 class(es), 61 assertion(s), and the four new lines read (mainnet, read from the branch on 2026-10-12: all 61 assertions matched):

    text
    ok   stakewise-oseth-exit-queue redeemer()             0xc43a7b16a7a167c0318390cba16787c11e9e1fd0
    ok   stakewise-oseth-exit-queue eip1967.implementation 0x0000000000000000000000000000000000000000
    ok   stakewise-oseth-exit-queue positionsManager()     0xf900c827cdabffb24fed00354579131516dace28
    ok   stakewise-oseth-exit-queue exitQueueUpdateDelay() 43200

    The last three are report-only: a changed value prints as moved, adds a reported, not held line and still exits 0. A non-zero slot means a proxy now stands at the redeemer's address: read the new code's enterExitQueue, claimExitedAssets, calculateExitedAssets and events before going on. A drift on the hard line (OsTokenConfig naming another redeemer: StakeWise redeployed it, and requests now go elsewhere) holds the escrow cursor: stop before step 3 and find out why.

  4. GATED: sweep the escrow stream from the floor to its live cursor, so the new filter's history is ingested (attended; idempotent upserts, archive RPC; the other filters re-read stored rows):

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    TO=$(psql "$DATABASE_URL" -tAc "SELECT last_scanned_block FROM onchain_credit.chain_scan_cursors WHERE chain_id = 1 AND scope = 'ledger:escrow'")
    npx tsx scripts/backfill-event-ledger.ts --stream escrow --from 24136053 --to "$TO" --dry-run
    npx tsx scripts/backfill-event-ledger.ts --stream escrow --from 24136053 --to "$TO"

    (From 24,136,053, the floor: nothing of this class exists below block 24,923,158.) Check, read-only: SELECT topic0, count(*), min(block_number) FROM onchain_credit.raw_events WHERE chain_id = 1 AND stream = 'escrow' AND address = '0xc43a7b16a7a167c0318390cba16787c11e9e1fd0' GROUP BY 1 returns the requests (0x211091c5…, 91 to block 26,175,689, the first at block 25,067,970) and the claims (0xeb3b05c0…, 86, the first at block 26,034,764); the redeemer's other events (checkpoints, position redemptions, swaps, ownership) are not scanned.

  5. GATED: re-measure the stream's history band over the thirteen filters, from the second provider:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    LEDGER_VERIFY_RPC_URL=<second provider> \
      npx tsx scripts/record-ledger-backfill-band.ts --stream escrow --to 25828233 \
        --note "<date> StakeWise's osETH redeemer joins the escrow stream" --window 5000 --dry-run
    # then the same with --confirm in place of --dry-run

    Expect the stored escrow rows over the band's range before step 3 plus StakeWise's 1 inside it (the one request at block 25,067,970; every other request and claim is after block 25,828,233). Read the first figure before step 3, read-only, with the band's floor:

    sql
    SELECT count(*) FROM onchain_credit.raw_events
     WHERE chain_id = 1 AND stream = 'escrow' AND block_number BETWEEN 24136053 AND 25828233;

    The band this step records must equal it plus 1. In v0.87.0, which carries Saturn's class too, one band covers both: that figure plus 5,117 (Saturn's 5,116 and this 1), 176,760 over 15 declared addresses (the combined pass, step 9).

  6. GATED: the completion run, which judges the corpus against step 4's band and promotes the certificate, the new key included:

    bash
    npx tsx scripts/backfill-event-ledger.ts --stream escrow
    npx tsx scripts/backfill-event-ledger.ts --verify --stream escrow   # read-only

    Expect one more escrow coverage row than before (the redeemer's, live) and a verify PASS; in v0.87.0, two more (the redeemer's and Saturn's queue's): 11 coverage row(s) stamped live from 24136053, with no --sample (the combined pass, step 10). A refusal publishes nothing and names its reason; do not answer it by re-running.

  7. GATED: after step 5, take the wallet list (read-only), then re-derive those wallets from their floor, and only those: every enrolled wallet that ever moved osETH (a request sends it to the redeemer; a swap buys it from the redeemer, which this release books as an exchange), and every wallet a swept request names as caller or receiver or a swept claim names:

    sql
    -- read-only: the wallet list for steps 6 and 7
    WITH w AS (SELECT uid, '0x000000000000000000000000' || substr(uid, 3) AS t FROM onchain_credit.accounts)
    SELECT w.uid
      FROM w
     WHERE EXISTS (SELECT 1 FROM onchain_credit.raw_events e
                    WHERE e.chain_id = 1 AND e.stream = 'wallet-token'
                      AND e.address = '0xf1c9acdc66974dfb6decb12aa385b9cd01190e38'
                      AND e.topic0 = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
                      AND (e.topic1 = w.t OR e.topic2 = w.t))
        OR EXISTS (SELECT 1 FROM onchain_credit.raw_events e
                    WHERE e.chain_id = 1 AND e.stream = 'escrow'
                      AND e.address = '0xc43a7b16a7a167c0318390cba16787c11e9e1fd0'
                      AND ((e.topic0 = '0x211091c5bf013c1230f996c3bb2bc327e3de429a3d3c356dcea9a0c858bc407f' AND (e.topic1 = w.t OR e.topic2 = w.t))
                        OR (e.topic0 = '0xeb3b05c070c24f667611fdb3ff75fe007d42401c573aed8d8faca95fd00ccb56' AND e.topic1 = w.t)))
     ORDER BY 1;

    Zero rows means steps 6 and 7 have nothing to do. Otherwise queue one whole-window rederive per listed wallet with the runbook's insert and read it done from portfolio_derive_jobs. Never before step 5: a re-derived wallet with a StakeWise movement then requires the missing certificate and withholds.

  8. Check, read-only, per re-derived wallet:

    sql
    SELECT block_number, venue, position_key, kind, amount_raw, consideration_raw, to_balance, link_id,
           meta->>'escrowStatus' AS status, meta->>'withheld' AS withheld
      FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND wallet = '<wallet>' AND link_kind = 'escrow'
       AND (position_key LIKE 'escrow:stakewise-oseth-exit-queue:%' OR meta->>'escrowClass' = 'stakewise-oseth-exit-queue')
     ORDER BY block_number, log_index, seq;

    Every request is one link_id (esc:1:0xc43a…1fd0:<ticket>) holding an internal_out on wallet:token:0xf1c9…0e38 (its consideration_raw the ether the ticket is born worth) and an internal_in on escrow:stakewise-oseth-exit-queue:<ticket>, and at its claim an internal_out on the ticket (its to_balance 0, its amount_raw what was paid) beside the ether internal_in; a partial claim's internal_out (statuspartial) states what was paid plus what moved on, beside an internal_in on the rest's ticket in the same link_id. No transfer_out of osETH to the redeemer and no transfer_in of a claim's ether remain, except a claim of a pre-window ticket no reading held (above). Zero held-back rows (withheld) for the class, the reconciler's line for the wallet (npx tsx scripts/ops/reconcile-ledger.ts --wallet <wallet>) clean, and on /portfolio an open ticket reads as an In settlement osETH row with a value in the ETH view. Then the issue's shared-code regression check: the two prod test wallets (0xdd647ce1…c737, 0xd1a557fe…6e09) still build their history completely (derive cursor present, zero held-back rows, their In settlement rows valued).

  9. Record executed: with the date, step 0's lines, step 2's output, step 5's coverage lines and step 7's rows.

Staging. Steps 0, 2 and 7's queries are read-only and safe there; the nightly reseed restores prod's raw_events and event_coverage, so a staging sweep is undone by the next reseed and proves nothing about prod (staging's data is a reseed).

Rollback. A code rollback does not roll back the database. The previous release reads no StakeWise leg, so a wallet holding the class's rows is refused by its escrow universe until it is re-derived under the previous code (which books the osETH sent to the redeemer and the ether received as transfers again). The ingested StakeWise logs, the redeemer's certificate row and migration 144's exit_queue value are inert under the previous code.

Saturn's sUSDat withdrawal queue, held in settlement (migration 140, #1087): prod steps, in order ​

  • belongs to: the escrow class saturn-susdat-withdrawal-queue (family saturn-queue; branch oc-1087-susdat), migration 140 (sUSDat's registry row names the class). Ships to prod in the SAME release as migration 141 (sUSDat's USD book, PR #1115)
  • executed: 2026-10-12
  • run record: (v0.87.0, release PR #1126, merge 1284e4c7 at 17:10:33Z on 2026-10-12, deploy run 38282474222 green 17:10:41Z to 17:11:55Z: app, ingester and worker restarted 17:11:53Z to 17:11:55Z, health 200, box on 0.87.0; 141 by hand at 17:10:13Z before the merge; one migrate.sh at 17:12:34Z to 17:12:41Z: 5 applied (140, 142, 143, 144 and #1124's 145), 144 total on disk; run as the combined pass.) Step 0 (17:09:56Z, read-only, run twice with the same answer): 15 accounts, every one answering; 14 read tickets_at_floor=0 tickets_now=0, and 0x5bc81274740a73d33ec8539182c326b8b58004c2 floor=25907400 tickets_at_floor=1 tickets_now=0: ticket 1330, requested at block 25,896,129 (before the wallet's floor) and claimed at 26,054,732 for 2,618.140255 USDat. That is the case a re-derive cannot recover: the claim stays money added (transfer_in of 2,618.140255 USDat at 26,054,732 after the re-derive), exactly as before the release. Step 1: sUSDat|queued|{ethereum}|saturn-susdat-withdrawal-queue. Step 2 (17:14Z): exit 0, 13 class(es), 61 assertion(s), Saturn's seven lines ok exactly as above (no moved), OK — 61 assertion(s) match the chain. Step 3 (one sweep with StakeWise's class): TO 26177750, 41 windows of 50,000, 11 certificate key(s), exit 0 at 17:17:38Z, range done [24136053,26177750] · 8662 new row(s); the queue's rows: requests 0xe6d14ce4… 1,741, processings 0x09d1133a… 1,722, claims 0x4ec90e96… 1,640, ticket transfers 0xddf252ad… 3,382, the first at block 24,836,599; no FundsSeized or RequestCancelled row. Step 4: B 171,643 before the sweep; inside the band 1,082 + 1,041 + 955 + 2,038 = 5,116; dry run measured 176760 … across 15 declared address(es), address list: escrow 15 address(es); recorded escrow=176760 over [24136053,25828233] (17:38:59Z). Step 5 (17:39:35Z to 17:39:52Z, no --sample): conditions 1 to 4 pass (176760 row(s) … vs [176760,176760], 0 stored row(s) on addresses in neither; 118 receipt(s), no gap; drawn from 34 current sweep record(s), 35 superseded), 11 coverage row(s) stamped live from 24136053, complete [24136053,25828233] · 0 new row(s); --verify --stream escrow: 11/11 declared address(es) live from the floor, verify PASS · run c1e832d0591d; coverage 7 rows live from 22,527,558 and 4 from 24,136,053. Step 6 (after step 10 and the worker's [restate] done: of 17:18:02Z): one wallet, 0x5bc81274…04c2 (StakeWise's list empty); job #2272 rederive [25907400,26177885] done 17:41:57Z (0 written, 165 unchanged). Its earlier restatement re-derive #2267 (17:18:02Z) had read partial … uncovered: escrow:0x4bc9…3d2e, the documented fail-closed shape before step 5. Step 7: ticket 1707 is one link_id esc:1:0x4bc9…3d2e:1707: at 26,140,508 an internal_out of 1,683.471248660101266739 sUSDat (consideration_raw 1742747360 USDat) beside the ticket's internal_in of 1742747360, at 26,146,594 the ticket's internal_out of 1751418270 (to_balance 0) beside USDat's internal_in of 1751418270; 0 withheld rows of the class; the reconciler for the wallet exit 0, no refused figure, book-overlays=0. Its follow-on audit #2273 reads partial … 4 unread … escrow:saturn-susdat-withdrawal-queue:1707 unread at 26140617,26142410 (two readings written under v0.86.0 while the ticket was open, before the class existed: the unread-legs class, no adjustment booked). Regression check: 0xdd647ce1…c737 derive cursor 26171977 and 0xd1a557fe…6e09 26150765, 0 held-back movement rows each, 74 and 319 escrow rows, reconciler exit 0 for both (0xdd647ce1's 93 withheld items are the standing self-check budget lines, as in v0.86.0). No enrolled wallet holds an open ticket now (tickets_now=0 everywhere), so no In settlement sUSDat row exists to look at; no browser check was approved for this run.

What it changes for a user, in one line: a wallet that redeems sUSDat keeps the value on its page through the wait, listed as sUSDat marked In settlement under Variable rate assets and worth what Saturn's queue will pay in USDat, in the All view and the USD view (sUSDat has the dollar book from migration 141, in the same release); its Activity reads one redemption ("Redemption requested" with the ticket's value, then "Redemption paid") instead of a withdrawal and, days later, a fresh deposit. Minting sUSDat with USDat is booked as an exchange of holdings.

What it does, and what it leaves.

  • Code, plus one additive registry update. The escrow class registry gains its twelfth class; the escrow stream gains one filter (the queue's WithdrawalRequested, WithdrawalProcessed, Claimed, FundsSeized, RequestCancelled and ERC-721 Transfer, six topics) and one certificate key (the queue, 0x4bc9fec04f0f95e9b42a3ef18f3c96fb57923d2e); the snapshot pass reads every wallet's tickets (getUserRequests, then each ticket's record, then sUSDat's previewRedeem for an unprocessed one); the derivation writes each redemption's movements. The registry check gains two storage reads (the two UUPS implementation slots) beside its multicall.
  • One release with migration 141. Without the dollar book an open request is half in the USD view (the ticket) and half outside it (the sUSDat that left), so its Activity line states no amount; with 141 both legs are in the dollar book and the line reads the ticket's value. And 141 without this class would leave open requests missing from the USD view while they wait (the reason its entry gives). So the two reach prod together: 141's steps 1 and 2 (applied by hand, then the plan) before the merge, then the deploy, then this entry's steps from 1 on.
  • The queue was deployed at block 24,629,457 (2026-03-10), after the coverage floor, so the sweep from the floor is its whole history: no ticket can predate the stored logs.
  • Between the deploy and step 5 the change fails closed, exactly as the Stader and Apyx releases did (Apyx's entry): a wallet whose reading holds an open ticket, or whose ledger holds a movement of this class the live ingester saw after the deploy, withholds (W7 uncertified-scope) until step 5 earns the certificate, then clears on its own. Run steps 2 to 5 straight after the deploy.
  • A redemption that straddles the deploy reads half old, half new until step 6: its request derived by the previous release (the sUSDat sent to the queue as money withdrawn) and its claim by this one, whose claim is then left as money added because the books never held the ticket. Step 6 takes its wallet list after step 5 for that reason.
  • What a re-derive recovers, and what it cannot. A request made inside the wallet's window is recovered: its request event is in the swept stream, so the re-derive books the request and its claim as one redemption, and a ticket received from another wallet inside the window enters at its value then. A ticket requested (or received) BEFORE the window and claimed inside it is closed only if a stored reading held it (the wallet's window-opening reading, or any reading the snapshot pass took while it was open). A reading taken before this release never holds a Saturn ticket, so for a wallet enrolled before the release with such a ticket, the claim's USDat stays money added (a deposit) and the sUSDat is the holding that left before the window, exactly as before the release. It is never closed from nothing: a ticket no reading valued would book its whole payout as a gain. Re-reading those wallets' opening readings is not built; step 0 lists them.
  • Where the ticket is charted (Fred's ruling, 2026-10-11). It is held in USDat, which has the dollar book, so it is in the USD view: until Saturn processes it the MTM PnL and Accrual only PnL lines move with sUSDat's value, and a fall in sUSDat's backing shows there. That is not a short window for most open tickets: at block 26,171,000, 22 tickets worth 517,060 USDat were unprocessed, and 20 of them (about $368k) were held by their holder's own price limit. Ticket 311 (312,178 USDat) has a limit 2.1% above the vault's value per share; five recent tickets (1726 to 1731, about $44k) are 0.2% to 0.4% above it; and 14 small tickets (1605 to 1689, about $12.5k) carry a queue v1/v2 limit on the TOTAL USDat that v3 reads as a per-share price, 10 to 8,700 times the value per share, so they never process until their holders act. The sUSDat a wallet still holds is in the USD view as well (migration 141, the same release).
  • sUSDat's pricing outages. Since sUSDat v4 its redemption value cannot be read while its STRC backing cannot be priced (blocks 26,110,049 to 26,110,609 on 2026-10-03, about two hours). A request, ticket transfer or cancellation in such a window is valued at the first block after it that prices, and that one movement is held back (the wallet's history goes on; the reconciler names it "a withdrawal ticket that could not be priced when it moved"). None of the 66 requests since v4 landed in one.

In release v0.87.0 this entry ships with StakeWise's, sUSDat's book, 142's, apxUSD and apyUSD's book and the coverage floor's last two steps, and they run as one order: the combined pass. Its order and numbers win where they differ from the steps below (one sweep, one band and one completion for both queues).

Prod, in order. Steps 3 to 7 write prod and need the owner's go.

  1. Before the deploy, read-only: which enrolled wallets held a Saturn ticket at their window start? For every account, the queue's balanceOf(wallet) at its history floor block (a floor before the queue's deployment holds none), and, for information, now. An account with no history floor of its own starts at the coverage floor (24,136,053), before the queue, so it held none at its start; it is still listed, with floor=none, for its tickets now:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    word() { curl -s -X POST -H 'content-type: application/json' "$ETHEREUM_ARCHIVE_RPC_URL" -d \
      "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"eth_call\",\"params\":[{\"to\":\"$1\",\"data\":\"0x70a08231000000000000000000000000${2:2}\"},\"$3\"]}" |
      sed -nE 's/.*"result":"0x([0-9a-f]{64})".*/\1/p'; }
    Q=0x4bc9fec04f0f95e9b42a3ef18f3c96fb57923d2e
    PGOPTIONS='-c default_transaction_read_only=on' psql "$DATABASE_URL" -tA -F' ' \
      -c "SELECT uid, coalesce(history_floor_block::text, 'none') FROM onchain_credit.accounts ORDER BY 1" |
    while read -r w b; do
      if [ "$b" = none ] || [ "$b" -lt 24629457 ]; then s=$(printf '%064x' 0); else s=$(word $Q "$w" "$(printf '0x%x' "$b")"); fi
      n=$(word $Q "$w" latest)
      if [[ "$s" =~ ^[0-9a-f]{64}$ && "$n" =~ ^[0-9a-f]{64}$ ]]; then
        echo "$w floor=$b tickets_at_floor=$((16#${s: -8})) tickets_now=$((16#${n: -8}))"
      else echo "$w floor=$b read_failed"; fi
    done

    A read_failed line: run it again until every wallet answers. A non-zero tickets_at_floor does not stop the release (the guard above keeps the payout from booking as a gain); name the wallet in the run record: its ticket is the case a re-derive cannot recover, and its claim stays money added. A non-zero tickets_now is a wallet that will show an In settlement sUSDat row once step 6 has run.

  2. The deploy (the release merge), and migration 140: one additive UPDATE of sUSDat's registry row (exit_queue = 'saturn-susdat-withdrawal-queue', redeem_networks restated unchanged). Unlike 141 it is safe after the deploy with no restart: the registry the app loads at start, and the ingester and the ledger worker re-read every five minutes (loadTokenRegistryRows, src/lib/data/registry-load.ts), does not read exit_queue or redeem_networks at all; their values come from the code's own registry, and the escrow class and its stream filter are code too. Applied by the standing runner after the deploy; check it, read-only:

    sql
    SELECT symbol, redeem_terms, redeem_networks, exit_queue
      FROM onchain_credit.portfolio_tokens
     WHERE chain_id = 1 AND address = '0xd166337499e176bbc38a1fbd113ab144e5bd2df7';
    -- sUSDat|queued|{ethereum}|saturn-susdat-withdrawal-queue

    redeem_terms already reads queued since migration 130 (the "atomic both ways" line in migration 111 is that migration's own frozen statement). Migration 141 touches other columns of the same row and was applied before the merge; the files apply in any order.

  3. The registry check, read-only:

    bash
    cd /opt/onchain-credit && ETHEREUM_RPC_URL="$(grep ^ETHEREUM_RPC_URL= .env.local | cut -d= -f2-)" \
      npm run verify:escrow-registry

    Exit 0, 13 class(es), 61 assertion(s) in v0.87.0, which carries StakeWise's class too (12 class(es), 57 assertion(s) on this branch alone, read on mainnet on 2026-10-11: all 57 assertions matched), and the seven new lines read:

    text
    ok   saturn-susdat-withdrawal-queue getWithdrawalQueue()   0x4bc9fec04f0f95e9b42a3ef18f3c96fb57923d2e
    ok   saturn-susdat-withdrawal-queue STAKED_USDAT()         0xd166337499e176bbc38a1fbd113ab144e5bd2df7
    ok   saturn-susdat-withdrawal-queue USDAT()                0x23238f20b894f29041f48d88ee91131c395aaa71
    ok   saturn-susdat-withdrawal-queue asset()                0x23238f20b894f29041f48d88ee91131c395aaa71
    ok   saturn-susdat-withdrawal-queue eip1967.implementation 0xdaf6f8523d7a707d173a12041e1523fdf1373f23
    ok   saturn-susdat-withdrawal-queue eip1967.implementation 0x2b7074cf6681382b70e239063931ebe83c0f4e0a
    ok   saturn-susdat-withdrawal-queue supportsInterface(bytes4)[0x780e9d63] 1

    The two implementation lines and the enumerability line are report-only: a changed value prints as moved, adds a reported, not held line and still exits 0. A moved implementation means Saturn upgraded the queue (three implementations, the last at block 26,091,045) or sUSDat (four, the last at the same block): read the new implementation's events, requestRedeem, processRequests, claim, requests and previewRedeem before going on, and re-pin it with that reading. A drift on any of the four hard lines (sUSDat minting into another queue, a queue naming another sUSDat or USDat) holds the escrow cursor: stop before step 3 and find out why.

  4. GATED: sweep the escrow stream from the floor to its live cursor, so the new filter's history is ingested (attended; idempotent upserts, archive RPC; the other filters re-read stored rows):

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    TO=$(psql "$DATABASE_URL" -tAc "SELECT last_scanned_block FROM onchain_credit.chain_scan_cursors WHERE chain_id = 1 AND scope = 'ledger:escrow'")
    npx tsx scripts/backfill-event-ledger.ts --stream escrow --from 24136053 --to "$TO" --dry-run
    npx tsx scripts/backfill-event-ledger.ts --stream escrow --from 24136053 --to "$TO"

    (From 24,136,053, the floor: nothing of this class exists below block 24,629,457.) Check, read-only: SELECT topic0, count(*), min(block_number) FROM onchain_credit.raw_events WHERE chain_id = 1 AND stream = 'escrow' AND address = '0x4bc9fec04f0f95e9b42a3ef18f3c96fb57923d2e' GROUP BY 1 returns the requests (0xe6d14ce4…, 1,732 to block 26,170,985), the processings (0x09d1133a…, 1,710), the claims (0x4ec90e96…, 1,633) and the ticket transfers (0xddf252ad…, 3,366), the first at block 24,836,599 (1,740, 1,722, 1,637 and 3,378 to block 26,177,184 on 2026-10-12: more is fine); no FundsSeized or RequestCancelled row exists (neither has ever been emitted).

  5. GATED: re-measure the stream's history band over the twelve filters (thirteen in v0.87.0), from the second provider:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    LEDGER_VERIFY_RPC_URL=<second provider> \
      npx tsx scripts/record-ledger-backfill-band.ts --stream escrow --to 25828233 \
        --note "<date> Saturn's withdrawal queue joins the escrow stream" --window 5000 --dry-run
    # then the same with --confirm in place of --dry-run

    Expect the stored escrow rows over the band's range before step 3 plus Saturn's 5,116 inside it (1,082 requests, 1,041 processings, 955 claims and 2,038 ticket transfers, all between blocks 24,836,599 and 25,828,233). Read the first figure before step 3, read-only, with the band's floor:

    sql
    SELECT count(*) FROM onchain_credit.raw_events
     WHERE chain_id = 1 AND stream = 'escrow' AND block_number BETWEEN 24136053 AND 25828233;

    The band this step records must equal it plus 5,116. In v0.87.0, which carries StakeWise's class too, one band covers both: that figure plus 5,117 (this 5,116 and StakeWise's 1), 176,760 over 15 declared addresses (the combined pass, step 9).

  6. GATED: the completion run, which judges the corpus against step 4's band and promotes the certificate, the new key included:

    bash
    npx tsx scripts/backfill-event-ledger.ts --stream escrow
    npx tsx scripts/backfill-event-ledger.ts --verify --stream escrow   # read-only

    Expect one more escrow coverage row than before (the queue's, live) and a verify PASS; in v0.87.0, two more (the queue's and StakeWise's redeemer's): 11 coverage row(s) stamped live from 24136053, with no --sample (the combined pass, step 10). A refusal publishes nothing and names its reason; do not answer it by re-running.

  7. GATED: after step 5, take the wallet list (read-only), then re-derive those wallets from their floor, and only those: every enrolled wallet that ever moved sUSDat (a request sends it to the queue; a deposit mints it, which this release books as an exchange), and every wallet a swept request or ticket transfer names:

    sql
    -- read-only: the wallet list for steps 6 and 7
    WITH w AS (SELECT uid, '0x000000000000000000000000' || substr(uid, 3) AS t FROM onchain_credit.accounts)
    SELECT w.uid
      FROM w
     WHERE EXISTS (SELECT 1 FROM onchain_credit.raw_events e
                    WHERE e.chain_id = 1 AND e.stream = 'wallet-token'
                      AND e.address = '0xd166337499e176bbc38a1fbd113ab144e5bd2df7'
                      AND e.topic0 = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
                      AND (e.topic1 = w.t OR e.topic2 = w.t))
        OR EXISTS (SELECT 1 FROM onchain_credit.raw_events e
                    WHERE e.chain_id = 1 AND e.stream = 'escrow'
                      AND e.address = '0x4bc9fec04f0f95e9b42a3ef18f3c96fb57923d2e'
                      AND ((e.topic0 = '0xe6d14ce42ad5a4efe0f111f81c1a1123db4ee41f561c3161e0960d54a9221ebe' AND e.topic2 = w.t)
                        OR (e.topic0 = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' AND (e.topic1 = w.t OR e.topic2 = w.t))))
     ORDER BY 1;

    Zero rows means steps 6 and 7 have nothing to do. Otherwise queue one whole-window rederive per listed wallet with the runbook's insert and read it done from portfolio_derive_jobs. Never before step 5: a re-derived wallet with a Saturn movement then requires the missing certificate and withholds.

  8. Check, read-only, per re-derived wallet:

    sql
    SELECT block_number, venue, position_key, kind, amount_raw, consideration_raw, to_balance, link_id, meta->>'withheld' AS withheld
      FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND wallet = '<wallet>' AND link_kind = 'escrow'
       AND (position_key LIKE 'escrow:saturn-susdat-withdrawal-queue:%' OR meta->>'escrowClass' = 'saturn-susdat-withdrawal-queue')
     ORDER BY block_number, log_index, seq;

    Every request is one link_id (esc:1:0x4bc9…3d2e:<ticket id>) holding an internal_out on wallet:token:0xd166…2df7 (its consideration_raw the USDat the ticket is born worth) and an internal_in on escrow:saturn-susdat-withdrawal-queue:<id>, and at its claim an internal_out on the ticket (its to_balance 0, its amount_raw what was paid) beside the USDat internal_in; a ticket received from or sent to another wallet is a transfer_in or transfer_out on the ticket. No transfer_out of sUSDat to the queue and no transfer_in of a claim's USDat remain, except a claim of a pre-window ticket no reading held (above). Zero held-back rows (withheld) for the class, the reconciler's line for the wallet (npx tsx scripts/ops/reconcile-ledger.ts --wallet <wallet>) clean, and on /portfolio an open ticket reads as an In settlement sUSDat row with a value, in the All view and the USD view. Then the issue's shared-code regression check: the two prod test wallets (0xdd647ce1…c737, 0xd1a557fe…6e09) still build their history completely (derive cursor present, zero held-back rows, their In settlement rows valued).

  9. Record executed: with the date, step 0's lines, step 2's output, step 5's coverage lines and step 7's rows.

Staging. Steps 0, 2 and 7's queries are read-only and safe there; the nightly reseed restores prod's raw_events and event_coverage, so a staging sweep is undone by the next reseed and proves nothing about prod (staging's data is a reseed).

Rollback. A code rollback does not roll back the database. The previous release reads no Saturn leg, so a wallet holding the class's rows is refused by its escrow universe until it is re-derived under the previous code (which books the sUSDat sent to the queue and the USDat received as transfers again). The ingested Saturn logs, the queue's certificate row and migration 140's exit_queue value are inert under the previous code.

Apyx's apyUSD unlock receipt, held in settlement (migration 139, #1087): prod steps, in order ​

  • belongs to: the escrow class apyx-apyusd-unlock-receipt (family apyx-receipt; branch oc-1087-apyusd), migration 139 (apyUSD's registry row names the class)
  • executed: 2026-10-11
  • run record: (v0.86.0, release PR #1114, merge 5da805f7, deploy run green 21:28:17Z to 21:29:29Z on 2026-10-11; migrate.sh applied 137, 138 and 139, 3 applied.) Step 0, before the merge (read-only): all 12 accounts open_receipts=0 legacy_unlock=none. Step 1 at 21:30Z: apyUSD|queued|{ethereum}|apyx-apyusd-unlock-receipt. Step 2 at 21:31Z: exit 0, 11 class(es), 50 assertion(s), the ten Apyx lines exactly as above, no moved line. Steps 3 to 5 ran once for both new classes, as the combined pass: the sweep stored 0x1baa6881… 1,151, 0xef951682… 1,010 and 0xddf252ad… 2,161 rows up to block 26,168,406, exactly the author's read (1,152, 1,017 and 2,169 up to the sweep's top, 26,171,852), the first at block 25,188,586; inside the band's range 886 + 796 + 1,682 = 3,364. The band recorded 171,643. The completion, pinned to 25186053, read condition 3 pass on [25186053,25236052] and stamped 9 coverage row(s) stamped live from 24136053 (the receipt's row live from 24136053); the pinned verify read verify PASS. Step 6's list (read-only, 21:56Z, after step 5): 0x272c39c8…2e2c, 0x5bc81274…04c2 and 0xaae6ae86…d050; their whole-window rederive jobs (#2081 to #2083) were done by 21:58:36Z. Step 7: 0x272c39c8…2e2c holds four redeems (receipts 993, 1014, 1121 and 1122), each one link_id with the internal_out on apyUSD and the internal_in on the receipt; 993 and 1014 were claimed (blocks 26,115,422 and 26,127,477) with the receipt's to_balance 0 and the apxUSD internal_in paying the receipt's full amount; 1121 and 1122 are open. Its four apyUSD burns to 0x0 are those internal_out rows and both apxUSD payouts are those internal_in rows: none is left as a transfer. 0x5bc81274…04c2 redeemed nothing (its apyUSD went to other addresses) and 0xaae6ae86…d050 moved no apyUSD inside its window. 0 held-back rows of the class on all three. The reconciler's lines for 0x5bc81274…04c2 and 0xaae6ae86…d050 are clean. The regression check is in Stader's record. OPEN, awaiting Fred's decision: two refused figures on 0x272c39c8…2e2c. The reconciler (exit 2) printed refused-figure … totalReturn refused=245.4087082 movements=2 escrow:apyx-apyusd-unlock-receipt:993 and … refused=938.8701114 movements=2 escrow:apyx-apyusd-unlock-receipt:1014. Why: no stored reading valued those two receipts during the wait (redeemed around 2026-09-14 and 09-15, claimed around 10-04 and 10-05), because every one of those readings predates the class, so the return over each wait ($245.41 and $938.87) is dropped and that stretch of the wallet's return line reads flat. These refusals are new with this re-derive (the 19:30Z self-check had none for the wallet), and the six-hourly self-check repeats them in its message on every run while they stand (keyed on the position, the line and the closing reading, so later runs read "open since"). Receipts 1121 and 1122 had no reading either at the time of the check: the newest reading, 18:00Z, predates the deploy.

What it changes for a user, in one line: a wallet that redeems apyUSD keeps the value on its page through the wait, listed in the All view (the USD view from 143) under Variable rate assets as apyUSD marked In settlement and worth the full apxUSD its receipt holds, and its Activity reads one redemption ("Redemption requested", then "Redemption paid") instead of a withdrawal and, days later, a fresh deposit. Minting apyUSD with apxUSD is booked as an exchange of holdings.

What it does, and what it leaves.

  • Code, plus one additive registry update. The escrow class registry gains its eleventh class; the escrow stream gains two filters (apyUSD's ReceiptIssued, one topic; the receipt's ReceiptClaimed and ERC-721 Transfer, two) and one certificate key (the receipt, 0x9bf51f33955ec70f87c4b5c49441815589043237); the snapshot pass reads every wallet's open receipts (the ids its stored receipt transfers name, completed against the receipt's balanceOf); the derivation writes each redemption's movements. The registry check gains a storage read (the two UUPS implementation slots) beside its multicall.
  • The receipt was deployed at block 25,131,190 (2026-05-19), after the coverage floor, so the sweep from the floor is its whole history: no receipt can predate the stored logs.
  • Between the deploy and step 5 the change fails closed, exactly as the Stader release did (its entry): a wallet whose reading holds an open receipt, or whose ledger holds a movement of this class the live ingester saw after the deploy, withholds (W7 uncertified-scope) until step 5 earns the certificate, then clears on its own. Run steps 2 to 5 straight after the deploy.
  • A redemption that straddles the deploy reads half old, half new until step 6: its redeem derived by the previous release (the apyUSD burned as money withdrawn) and its claim by this one, whose claim is then left as money added because the books never held the receipt. Step 6 takes its wallet list after step 5 for that reason.
  • What a re-derive recovers, and what it cannot. A redeem made inside the wallet's window is recovered: its request event is in the swept stream, so the re-derive books the redeem and its claim as one redemption. A receipt minted BEFORE the window and claimed inside it is closed only if a stored reading held it (the wallet's window-opening reading, or any reading the snapshot pass took while it was open). A reading taken before this release never holds an Apyx receipt, so for a wallet enrolled before the release with such a receipt, the claim's apxUSD stays money added (a deposit) and the apyUSD is the holding that left before the window, exactly as before the release. It is never closed from nothing: a receipt no reading valued would book its whole payout as a gain. Re-reading those wallets' opening readings is not built; step 0 checks that no wallet needs it, and a non-zero line stops the release.
  • apyUSD's older exit is not part of this release. Before 2026-05-27 a redeem paid an ERC-20 apxUSD_unlock (0x93775e2d…f4e6) instead of a receipt; 14 wallets still held 194.51 of it on 2026-10-11. creddit does not track that token, so a holding of it is not on the books and its claim lands as apxUSD added, as today. Step 0 prints any enrolled wallet holding it, for information.

Prod, in order. Steps 3 to 7 write prod and need the owner's go. In release v0.86.0 this entry ships with Stader's and the coverage floor's, and the three run as one order: the combined pass at the end of this entry. Its order and numbers win where they differ from the steps below, which are written as if this entry shipped alone.

  1. Before the deploy, read-only: does any enrolled wallet hold an Apyx receipt at its window start? For every account, the receipt's balanceOf(wallet) at its history floor block (a floor before the receipt's deployment holds none), and, for information only, its apxUSD_unlock balance now:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    word() { curl -s -X POST -H 'content-type: application/json' "$ETHEREUM_ARCHIVE_RPC_URL" -d \
      "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"eth_call\",\"params\":[{\"to\":\"$1\",\"data\":\"0x70a08231000000000000000000000000${2:2}\"},\"$3\"]}" |
      sed -nE 's/.*"result":"0x([0-9a-f]{64})".*/\1/p'; }
    PGOPTIONS='-c default_transaction_read_only=on' psql "$DATABASE_URL" -tA -F' ' \
      -c "SELECT uid, history_floor_block FROM onchain_credit.accounts WHERE history_floor_block IS NOT NULL ORDER BY 1" |
    while read -r w b; do
      if [ "$b" -lt 25131190 ]; then r=$(printf '%064x' 0); else r=$(word 0x9bf51f33955ec70f87c4b5c49441815589043237 "$w" "$(printf '0x%x' "$b")"); fi
      u=$(word 0x93775e2dfa4e716c361a1f53f212c7ae031bf4e6 "$w" latest)
      if [[ "$r" =~ ^[0-9a-f]{64}$ && "$u" =~ ^[0-9a-f]{64}$ ]]; then
        echo "$w floor=$b open_receipts=$((16#${r: -8})) legacy_unlock=$([ "$u" = "$(printf '%064x' 0)" ] && echo none || echo held)"
      else echo "$w floor=$b read_failed"; fi
    done

    Every line reads open_receipts=0. A read_failed line: run it again until every wallet answers. A non-zero open_receipts: stop, do not deploy, and bring the wallet to Fred (above: this release does not handle it, and what its page would show was not tested). A legacy_unlock=held changes nothing here; name the wallet in the run record.

  2. The deploy (the release merge), and migration 139: one additive UPDATE of apyUSD's registry row (exit_queue = 'apyx-apyusd-unlock-receipt'), safe before or after the deploy (nothing reads the column at run time). Applied by the standing runner after the deploy; check it, read-only:

    sql
    SELECT symbol, redeem_terms, redeem_networks, exit_queue
      FROM onchain_credit.portfolio_tokens
     WHERE chain_id = 1 AND address = '0x38eeb52f0771140d10c4e9a9a72349a329fe8a6a';
    -- apyUSD|queued|{ethereum}|apyx-apyusd-unlock-receipt

    Migrations 137 (Stader) and 138 (the coverage floor) touch other objects; the files apply in any order.

  3. The registry check, read-only:

    bash
    cd /opt/onchain-credit && ETHEREUM_RPC_URL="$(grep ^ETHEREUM_RPC_URL= .env.local | cut -d= -f2-)" \
      npm run verify:escrow-registry

    Exit 0, 11 class(es), 50 assertion(s), and the ten new lines read (mainnet, read from the branch on 2026-10-11: all 50 assertions matched):

    text
    ok   apyx-apyusd-unlock-receipt receipt()              0x9bf51f33955ec70f87c4b5c49441815589043237
    ok   apyx-apyusd-unlock-receipt vault()                0x38eeb52f0771140d10c4e9a9a72349a329fe8a6a
    ok   apyx-apyusd-unlock-receipt asset()                0x98a878b1cd98131b271883b390f68d2c90674665
    ok   apyx-apyusd-unlock-receipt asset()                0x98a878b1cd98131b271883b390f68d2c90674665
    ok   apyx-apyusd-unlock-receipt eip1967.implementation 0x54f1c7ffe10bc392f08ae9432a7e21a6e86bb982
    ok   apyx-apyusd-unlock-receipt eip1967.implementation 0xfd616567ecc1607f61073951a1e822f7315bb112
    ok   apyx-apyusd-unlock-receipt feeCurve()             34000000000000000
    ok   apyx-apyusd-unlock-receipt feeCurve()             259200
    ok   apyx-apyusd-unlock-receipt feeCurve()             1728000
    ok   apyx-apyusd-unlock-receipt supportsInterface(bytes4)[0xb45a3c0e] 1

    The two implementation lines, the three feeCurve() words and the soulbound declaration are report-only: a changed value prints as moved, adds a reported, not held line and still exits 0. A moved implementation means Apyx upgraded the receipt (one implementation since deployment) or apyUSD (four, the last at block 25,188,571): read the new implementation's events, redeem / _withdraw, claim and getReceipt before going on, and re-pin it with that reading. A moved fee curve changes when receipts become claimable and what an early claim costs, both read live, and nothing the class values. A drift on any of the four hard lines (apyUSD minting into another receipt, a receipt with another vault or asset) holds the escrow cursor: stop before step 3 and find out why.

  4. GATED: sweep the escrow stream from the floor to its live cursor, so the new filters' history is ingested (attended; idempotent upserts, archive RPC; the other filters re-read stored rows):

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    TO=$(psql "$DATABASE_URL" -tAc "SELECT last_scanned_block FROM onchain_credit.chain_scan_cursors WHERE chain_id = 1 AND scope = 'ledger:escrow'")
    npx tsx scripts/backfill-event-ledger.ts --stream escrow --from 24136053 --to "$TO" --dry-run
    npx tsx scripts/backfill-event-ledger.ts --stream escrow --from 24136053 --to "$TO"

    (From 24,136,053, the coverage floor: nothing of this class exists below block 25,131,190.) The sweep prints one line per window, [backfill-ledger/escrow] [<from>,<to>] wrote N · progress …; keep the output, because step 5 pins its check to one of these windows. Check, read-only: SELECT address, topic0, count(*), min(block_number) FROM onchain_credit.raw_events WHERE chain_id = 1 AND stream = 'escrow' AND address IN ('0x38eeb52f0771140d10c4e9a9a72349a329fe8a6a', '0x9bf51f33955ec70f87c4b5c49441815589043237') GROUP BY 1, 2 returns apyUSD's 0x1baa6881… (receipts issued, 1,151 to block 26,168,406), the receipt's 0xef951682… (claims, 1,010) and its 0xddf252ad… (mints and burns, 2,161), the first at block 25,188,586.

  5. GATED: re-measure the stream's history band over the eleven filters, from the second provider:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    LEDGER_VERIFY_RPC_URL=<second provider> \
      npx tsx scripts/record-ledger-backfill-band.ts --stream escrow --to 25828233 \
        --note "<date> Apyx's unlock receipt joins the escrow stream" --window 5000 --dry-run
    # then the same with --confirm in place of --dry-run

    Expect the stored escrow rows over the band's range before step 3 plus Apyx's 3,364 inside it (886 receipts issued, 796 claims and 1,682 transfers, all between blocks 25,188,586 and 25,828,233). Read the first figure before step 3, read-only:

    sql
    SELECT count(*) FROM onchain_credit.raw_events
     WHERE chain_id = 1 AND stream = 'escrow' AND block_number BETWEEN 24136053 AND 25828233;

    The band this step records must equal it plus 3,364 (in v0.86.0, plus Stader's rows as well: the combined pass, step 8).

  6. GATED: the completion run, which judges the corpus against step 4's band and promotes the certificate, the new key included:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    PIN=$(psql "$DATABASE_URL" -tAc "SELECT from_block FROM onchain_credit.chain_scan_ranges
      WHERE chain_id = 1 AND scope = 'ledger:escrow:backfill' AND from_block BETWEEN 24136053 AND 25188586
      ORDER BY scanned_at DESC LIMIT 1")   # read-only; 25186053 at the default 50,000-block window
    LEDGER_VERIFY_RPC_URL=<second provider> npx tsx scripts/backfill-event-ledger.ts --stream escrow --sample "$PIN"
    LEDGER_VERIFY_RPC_URL=<second provider> npx tsx scripts/backfill-event-ledger.ts --verify --stream escrow --sample "$PIN"   # read-only

    Both runs pin condition 3 to a record step 3 wrote, and every later escrow --verify does too (why, and how to read the pin): left to a random draw, the check picks one of the earlier sweeps' records (about half the time in v0.86.0), and those cannot reproduce under this release's filters. Expect one more escrow coverage row than before (the receipt's, live), condition 3's line naming [<PIN>,…] and reading pass, and a verify PASS. A refusal publishes nothing and names its reason; do not answer it by re-running.

  7. GATED: after step 5, take the wallet list (read-only), then re-derive those wallets from their floor, and only those: every enrolled wallet that ever moved apyUSD (a redeem burns it; a deposit mints it, which this release books as an exchange), and every wallet a swept receipt names as its owner:

    sql
    -- read-only: the wallet list for steps 6 and 7
    WITH w AS (SELECT uid, '0x000000000000000000000000' || substr(uid, 3) AS t FROM onchain_credit.accounts)
    SELECT w.uid
      FROM w
     WHERE EXISTS (SELECT 1 FROM onchain_credit.raw_events e
                    WHERE e.chain_id = 1 AND e.stream = 'wallet-token'
                      AND e.address = '0x38eeb52f0771140d10c4e9a9a72349a329fe8a6a'
                      AND e.topic0 = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
                      AND (e.topic1 = w.t OR e.topic2 = w.t))
        OR EXISTS (SELECT 1 FROM onchain_credit.raw_events e
                    WHERE e.chain_id = 1 AND e.stream = 'escrow'
                      AND e.address = '0x38eeb52f0771140d10c4e9a9a72349a329fe8a6a'
                      AND e.topic0 = '0x1baa688106ed355089d61aca6f31cdb5758b11deb7e73b3cb7d1db8efd8b2d43'
                      AND e.topic1 = w.t)
     ORDER BY 1;

    Zero rows means steps 6 and 7 have nothing to do. Otherwise queue one whole-window rederive per listed wallet with the runbook's insert and read it done from portfolio_derive_jobs. Never before step 5: a re-derived wallet with an Apyx movement then requires the missing certificate and withholds.

  8. Check, read-only, per re-derived wallet:

    sql
    SELECT block_number, venue, position_key, kind, amount_raw, consideration_raw, to_balance, link_id, meta->>'withheld' AS withheld
      FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND wallet = '<wallet>' AND link_kind = 'escrow'
       AND (position_key LIKE 'escrow:apyx-apyusd-unlock-receipt:%' OR meta->>'escrowClass' = 'apyx-apyusd-unlock-receipt')
     ORDER BY block_number, log_index, seq;

    Every redeem is one link_id (esc:1:0x9bf5…3237:<receipt id>) holding an internal_out on wallet:token:0x38ee…8a6a (its consideration_raw the apxUSD the receipt escrows) and an internal_in on escrow:apyx-apyusd-unlock-receipt:<id>, and at its claim an internal_out on the receipt (its to_balance 0, its amount_raw what was paid, so an early claim's fee is the gap to the receipt's last reading) beside the apxUSD internal_in; a claim the holder sent to another address is a transfer_out on the receipt instead. No transfer_out of apyUSD to 0x0 and no transfer_in of a claim's apxUSD remain, except a claim of a pre-window receipt no reading held (above). Zero held-back rows (withheld) for the class, the reconciler's line for the wallet (npx tsx scripts/ops/reconcile-ledger.ts --wallet <wallet>) clean, and on /portfolio (All view, Variable rate assets) an open receipt reads as an In settlement apyUSD row with a value. Then the issue's shared-code regression check: the two prod test wallets (0xdd647ce1…c737, 0xd1a557fe…6e09) still build their history completely (derive cursor present, zero held-back rows, their In settlement rows valued).

  9. Record executed: with the date, step 0's lines, step 2's output, step 5's coverage lines and step 7's rows.

Staging. Steps 0, 2 and 7's queries are read-only and safe there; the nightly reseed restores prod's raw_events and event_coverage, so a staging sweep is undone by the next reseed and proves nothing about prod (staging's data is a reseed).

Rollback. A code rollback does not roll back the database. The previous release reads no Apyx leg, so a wallet holding the class's rows is refused by its escrow universe until it is re-derived under the previous code (which books the apyUSD burned and the apxUSD received as transfers again). The ingested Apyx logs, the receipt's certificate row and migration 139's exit_queue value are inert under the previous code.

Release v0.86.0: the three entries as one prod order ​

v0.86.0 carries this entry, Stader's and the coverage floor's. They share one escrow sweep, one band, one completion run and one re-derive, so they run as this one order. Each entry's own step holds the query and what its lines mean; the numbers here are the ones that hold when all three ship together, and they win where an entry differs. GATED steps write prod and need Fred's go. Steps 11 and 12 did not finish in v0.86.0 (they wait for migration 142); they run in v0.87.0 as step 15 of its combined pass, whose numbers (784,903 across 640, escrow unpinned at 176,760) replace the ones below.

  1. Before the merge, read-only: Stader step 1 (every line open_requests=0) and Apyx step 0 (every line open_receipts=0; a legacy_unlock=held is information only). Any non-zero line: stop, do not merge.

  2. The merge (a merge commit), the prod deploy, health 200. The deploy restarts the ingester.

  3. GATED: one migrate.sh run (coverage floor step 1): 3 applied (137, 138, 139). Then the three read-only checks: ETHx|queued|{ethereum}|stader-ethx-withdraw-queue (Stader step 2), apyUSD|queued|{ethereum}|apyx-apyusd-unlock-receipt (Apyx step 1) and declared_addresses|integer|YES (coverage floor step 1).

  4. The ingester (coverage floor step 2): no cycle error, per-stream scanned lines, no catch-up line naming a floor below 24136053.

  5. The registry check (Apyx step 2): exit 0, 11 class(es), 50 assertion(s), Stader's seven lines (its step 3) and Apyx's ten all ok. (Counted from this release's registry: 11 classes, 50 assertions, 7 of them Stader's and 10 Apyx's.)

  6. Read-only, right before the sweep: the baseline B, every escrow row over the band's range, which at this point holds neither new class:

    sql
    SELECT count(*) FROM onchain_credit.raw_events
     WHERE chain_id = 1 AND stream = 'escrow' AND block_number BETWEEN 24136053 AND 25828233;

    166,457 when the release review read it on prod on 2026-10-11. Only a sweep writes escrow rows that far below the live cursor, so expect the same figure; use the one you read as B.

  7. GATED: one sweep for both classes, Apyx step 3's two commands (--stream escrow --from 24136053 --to "$TO", dry run first). Keep the output: its window lines give the pin. Then, read-only:

    • Stader (its step 4's query): both topics, 0x5b2ce385… and 0xc41189bc…, present, and min(block_number) >= 24136053.

    • Apyx (its step 3's query): 0x1baa6881… at least 1,151, 0xef951682… at least 1,010 and 0xddf252ad… at least 2,161, the first at block 25,188,586 (the Apyx author's chain read to block 26,168,406; the sweep runs past that block, so more is fine).

    • S, A and the stored count over the band's range:

      sql
      SELECT count(*) FILTER (WHERE address = '0x9f0491b32dbce587c50c4c43ab303b06478193a7') AS s,
             count(*) FILTER (WHERE address IN ('0x38eeb52f0771140d10c4e9a9a72349a329fe8a6a',
                                                '0x9bf51f33955ec70f87c4b5c49441815589043237')) AS a,
             count(*) AS stored
        FROM onchain_credit.raw_events
       WHERE chain_id = 1 AND stream = 'escrow' AND block_number BETWEEN 24136053 AND 25828233;

      a reads 3,364 (886 receipts issued, 796 claims, 1,682 transfers: the Apyx author's chain read) and stored = B + s + a. A stored above that means the sweep also filled rows of an older class (as v0.85.0's filled six Maple logs): stop and read them before step 8. s is not pinned in advance (nobody has counted the 2026 part of Stader's history); step 8's independent measurement judges it.

    • The pin, PIN: read it as below (25186053 at the default window).

  8. GATED: the band, from the second provider (Apyx step 4's command: --stream escrow --to 25828233 --window 5000, with a note naming both classes). The measured count over [24136053,25828233] equals step 7's stored: 166,457 + S + 3,364 (with step 6's B in place of 166,457). Any other figure: stop and find why, as on 2026-10-09. Then --confirm.

  9. GATED: the completion run, pinned (Apyx step 5's two commands, --sample "$PIN" on both): condition 1 exact, condition 3 pass on [<PIN>,…], 9 coverage row(s) stamped live from 24136053, then verify PASS. Read-only, SELECT address, from_block, status FROM onchain_credit.event_coverage WHERE chain_id = 1 AND stream = 'escrow' AND address <> '*' ORDER BY 1: nine rows, all live; the seven older keys still read 22527558 (a stamp keeps the lower bottom), the manager (0x9f04…93a7) and the receipt (0x9bf5…3237) read 24136053.

  10. GATED, after step 9 and never before: one re-derive list for both classes. Run Stader step 7's query and Apyx step 6's query; the list is the union of the two (a wallet on both is re-derived once). Queue one whole-window rederive per wallet (the runbook's insert) and read each done; then Stader step 8's and Apyx step 7's checks per wallet, and the two prod test wallets' regression check once.

  11. GATED: erc4626's re-measure (coverage floor step 3), over [24136053,25840566], hours, after migration 142's release: every key live (648 or more, 639 or more once the nine retired rows are removed), measured = the stored rows on the declared set (784,817 or more across 639 or more on 2026-10-11), with an address list of the same count.

  12. Read-only: the acceptance gate over every stream (coverage floor step 4): header floor 24136053; escrow's verdict from its own pinned run, over [24136053,25828233]; erc4626 over [24136053,25840566], condition 1 exact at step 11's N with 7793 stored row(s) on addresses in neither, not counted, its condition 3 read as that step says; the other eleven over [22527558, …]; wallet-token 12/12 … with 0xef08… not enrolled.

  13. Record executed: on all three entries, in one docs PR, each with its own lines.

Run record, 2026-10-11 (v0.86.0, merge 5da805f7). Steps 1 to 10 ran; step 11 stopped at its dry run; steps 11 to 13 re-run after migration 142's release (commit 1494b3a2 on staging, Fred's decision of 2026-10-12). Box outputs are in /var/tmp/v0860/ on the prod box.

StepExpectedRead
1every line open_requests=0 and open_receipts=0all 12 accounts, both checks; legacy_unlock=none on all 12
2merge, deploy, health 200deploy run green 21:28:17Z to 21:29:29Z; box on 0.86.0; health 200
33 applied and three rows3 applied (137, 138, 139); the three rows exactly
4no cycle error, no catch-up below 24136053restarted 21:29:25Z; 0 cycle error; no catch-up line
5exit 0, 11 class(es), 50 assertion(s)exactly; all 50 ok, no moved
6B = 166,457166,457 (21:31Z)
7sweep; Apyx at least 1,151 / 1,010 / 2,161 from 25,188,586; a = 3,364; stored = B + s + aTO 26171852, 41 windows 21:32:01Z to 21:34:52Z, exit 0, 6550 new row(s); Stader 1,156 requests and 1,057 claims from block 24,136,262; Apyx exactly 1,151 / 1,010 / 2,161 to 26,168,406, first at 25,188,586; s = 1,822, a = 3,364, stored = 171,643 = 166,457 + 1,822 + 3,364
7 (pin)25186053, scanned_at inside the sweep, log_count above 025186053|25236052|5237|21:33:36Z, the sweep's [25186053,25236052] wrote 193 line
8measured = 166,457 + S + 3,364 = 171,643dry run measured 171643 … across 13 declared address(es) (21:35:56Z to 21:44:59Z); recorded escrow=171643 over [24136053,25828233] at 21:54:29Z, superseding 313,819 over [22527558,25828233]
9condition 1 exact, condition 3 pass on [<PIN>,…], 9 rows, verify PASS21:55Z: 171643 vs [171643,171643], condition 2 118 receipts no gap, condition 3 pass on [25186053,25236052], 9 coverage row(s) stamped live from 24136053, complete [24136053,25828233] · 0 new row(s); verify verify PASS · run c1e832d0591d; seven rows at 22527558, the manager and the receipt at 24136053, all live
10union list re-derived after step 9; per-wallet checks cleanStader: 0xdd647ce1…c737; Apyx: 0x272c39c8…2e2c, 0x5bc81274…04c2, 0xaae6ae86…d050; jobs #2081 to #2084 done 21:57Z to 21:59Z; rows as each entry's record says; OPEN: two refused figures on 0x272c39c8…2e2c (Apyx's record)
11648 or more keys live; measured = stored (792,610 or more)648 of 648 live, 792,610 stored; dry run measured 784,817 across 639 declared addresses: stopped, not confirmed (the coverage floor's record: the 7,793 rows are retired stUSDS's history); re-runs after migration 142's release
12every stream's verdictnot run: it needs step 11's band (after migration 142's release)

Pinning escrow's sampled check after this release's sweep ​

Why. Condition 3 of the acceptance gate re-scans one stored sweep record (a block range, its log count and a digest of its logs) on the second provider, with today's filters, and compares the digests. Without --sample it draws the record at random from every escrow sweep record that overlaps the band's range. Records are keyed by their first block. The earlier escrow sweeps (v0.85.0's the last) ran from 22,527,558 in 50,000-block windows; this release's runs from 24,136,053, which is 1,608,495 blocks higher and not a multiple of 50,000, so it overwrites none of them. After the sweep 69 records overlap [24136053,25828233]: the 34 it wrote (24,136,053 + 50,000 × k, k = 0 to 33) and 35 earlier ones (22,527,558 + 50,000 × k, k = 32 to 66) whose digests cover nine classes. Stader's manager logs requests and claims in nearly every 2026 window, so an earlier record re-scanned with eleven classes mismatches: condition 3 MISS, and the completion refuses and publishes nothing. A random draw does that about half the time (35 of 69). It is not a hole, and re-running only draws again.

Which record, and how to read it. Any record this sweep wrote works. The one holding Apyx's first logs (block 25,188,586) also holds Stader logs, so its check covers both new filters. Two ways to read it, with the same answer:

  • From the sweep's output: the window line whose range holds block 25,188,586, [backfill-ledger/escrow] [25186053,25236052] wrote N · progress … at the default window. The pin is its first block. 25,186,053 is 24,136,053 + 21 × 50,000; the window is --window when given, else BACKFILL_WINDOW from the environment (which .env.local could set), else 50,000, so on any other window the line, not this number, is the pin.

  • Read-only, from the records (Apyx step 5's PIN=$(…) is the same query, first column only):

    sql
    SELECT from_block, to_block, log_count, scanned_at FROM onchain_credit.chain_scan_ranges
     WHERE chain_id = 1 AND scope = 'ledger:escrow:backfill' AND from_block BETWEEN 24136053 AND 25188586
     ORDER BY scanned_at DESC LIMIT 1;
    -- 25186053|25236052|<N>|<a time during the sweep>   (default window)

    scanned_at falls inside the sweep's run and to_block is at or above 25,188,586; anything else is not this sweep's record, so read the sweep's output instead.

What --sample does (scripts/backfill-event-ledger.ts): spelled --sample N or --sample=N; a missing, empty or non-numeric value is refused before anything runs (so an unset $PIN in a new shell stops the run rather than drawing at random: re-read it). It replaces the random draw on both the completion run and --verify: condition 3 re-checks the sweep record that starts at exactly block N among those overlapping the band's range. If none starts there, condition 3 misses with no backfill receipt to sample (from v0.87.0: no backfill receipt starts at block N (--sample)); it never falls back to a random record. It applies to every stream the run covers, so --sample on a run over all streams makes every other stream miss that way: run escrow on its own with the pin.

Fixed in code in v0.87.0 (commit 01c371f3): condition 3 samples only the newest record per block range (currentReceipts in scripts/lib/ledger-backfill.ts). A sweep record is drawn, or accepted as a pin, only when no sweep record written later (scanned_at) overlaps any block of it; the earlier grid's records that a newer sweep overlaps are skipped, never drawn, and never substituted. Supersession is judged over every sweep record overlapping the candidates, re-read over their whole span, so a record straddling the band's edge is judged against a newer one past the edge too. The verdict line says how many records the draw was over: [F,T] digest compared against independent provider · drawn from 34 current sweep record(s), 35 superseded by newer overlapping ones not sampled on v0.86.0's escrow shape. So:

  • Later escrow classes need no pin (Saturn's and StakeWise's, in v0.87.0, are the first): drop --sample "$PIN" from their completion run and --verify, and from the coverage floor's step 4 (v0.87.0's combined pass, steps 10 and 15). A sweep from the class's first block upward, on any window, writes records newer than every earlier one it overlaps, and the earlier records it does not overlap hold none of the new class's logs.
  • --sample keeps working for a repeatable re-check, on a current record. 25186053 stays valid while nothing newer overlaps it: a later sweep from 24,136,053 on the default 50,000-block window rewrites that same record, so it stays current; a sweep on any other window supersedes it. A pin on a record a newer one overlaps is refused by name: --sample N names [N,…], superseded by [F,T] scanned later (<time>); pin a current record.
  • v0.86.0's own steps above ran on v0.86.0's code, with the pin as written (2026-10-11). From v0.87.0 no escrow pin is needed anywhere.
  • What newest-per-range does not cover: a record that is the newest of its blocks but was taken over a smaller filter or address set than today's. No later sweep record overlaps it, so it stays drawable. That is erc4626's case (and any stream whose declared set grew with no re-sweep): its records predate the ~100 vaults the ingester caught up, which writes rows but no sweep record. It keeps the refresh-and-pin procedure (step 4), and after the refresh the pin is still needed, because an unpinned draw can land on a record not refreshed. The records do not store the filter set they were taken over, so the code cannot tell these apart; storing a fingerprint of it on each record is the fix, and is not built.

Stader's ETHx withdrawal, held in settlement (migration 137, #1087): prod steps, in order ​

  • belongs to: the escrow class stader-ethx-withdraw-queue (family stader-queue; branch oc-1087-ethx), migration 137 (ETHx's registry row names the class)
  • executed: 2026-10-11
  • run record: (v0.86.0, release PR #1114, merge 5da805f7, deploy run green 21:28:17Z to 21:29:29Z on 2026-10-11; migrate.sh applied 137, 138 and 139, 3 applied.) Step 1, before the merge (read-only): all 12 accounts open_requests=0. Step 2 at 21:30Z: ETHx|queued|{ethereum}|stader-ethx-withdraw-queue. Step 3 at 21:31Z: exit 0, 11 class(es), 50 assertion(s), the seven Stader lines exactly as above, no moved line, all 50 matching the chain. Steps 4 to 6 ran once for both new classes, as the combined pass (its record has the shared figures): the sweep --from 24136053 --to 26171852 stored the manager's requests 0x5b2ce385… (1,156 rows, the first at block 24,136,262) and claims 0xc41189bc… (1,057, the first at 24,138,026), S = 1,822 inside the band's range; the band recorded 171,643 = 166,457 + 1,822 + 3,364; the pinned completion stamped 9 coverage row(s) stamped live from 24136053, the manager's row live from 24136053, and the pinned verify read verify PASS. Step 7's list (read-only, 21:56Z, after step 6): one wallet, the prod test wallet 0xdd647ce1…c737, named by its three requests (blocks 25,572,748 to 25,572,754) whose claims (25,575,490 to 25,575,497) all fall before its floor 25,928,920, as foreseen above. Its whole-window rederive (job #2084) was done at 21:59Z. Step 8: the wallet holds no row of the class (nothing of it inside its window) and no ETHx transfer to the manager, 0 held-back rows, and the reconciler's line for it shows no refused figure and no identity failure (its held-back items over budget are the standing self-check alert open since 2026-10-08, unrelated to this class). Regression check (read-only, 22:01Z): both prod test wallets have their derive cursor (0xdd647ce1…c737 at 26171977 after the re-derive, 0xd1a557fe…6e09 at 26150765), 0 held-back movement rows, 74 and 319 escrow rows. The In settlement rows on /portfolio were not looked at in a browser (no browser check was approved for this run).

What it changes for a user, in one line: a wallet that asks Stader for its ETHx back keeps the value on its page through the wait, listed as ETHx marked In settlement and worth what the claim will pay, and its Activity reads one redemption ("Redemption requested", then "Redemption paid") instead of a withdrawal and, a week or two later, a fresh deposit. Minting ETHx with ether through Stader is booked as an exchange of holdings.

What it does, and what it leaves.

  • Code, plus one additive registry update. The escrow class registry gains its tenth class; the escrow stream gains one filter (the manager's request and claim, two topics) and one certificate key (the manager, 0x9f0491b32dbce587c50c4c43ab303b06478193a7); the snapshot pass reads every wallet's open Stader requests; the derivation writes each redemption's movements. The claim log names no request, so the derivation reads the owner's open-id list at the claim's block and the block before it (two archive reads per claiming block, plus one per request lost there).
  • Between the deploy and step 6 the change fails closed, exactly as the Renzo and wBETH releases did (Renzo's entry): a wallet whose reading holds an open Stader request, or whose ledger holds a movement of this class the live ingester saw after the deploy, withholds (W7 uncertified-scope) until step 6 earns the certificate, then clears on its own. Run steps 3 to 6 straight after the deploy.
  • A redemption that straddles the deploy reads half old, half new until step 7: its request derived by the previous release (the ETHx sent to the manager as money withdrawn) and its claim by this one, whose claim is then left as money added because the books never held the ticket. Step 7 takes its wallet list after step 6 for that reason.
  • What a re-derive recovers, and what it cannot. A request made inside the wallet's window is recovered: its request event is in the swept stream, so the re-derive books the request and its claim as one redemption. A request made BEFORE the window and claimed inside it is closed only if a stored reading held its ticket (the wallet's window-opening reading, or any reading the snapshot pass took while it was open). A reading taken before this release never holds a Stader ticket, so for a wallet enrolled before the release with such a request, the claim's ether stays money added (a deposit) and the ETHx is the holding that left before the window, exactly as before the release. It is never closed from nothing: a ticket no reading valued would book its whole payout as a gain. Re-reading those wallets' opening readings was not built because no wallet needs it: on 2026-10-09, none of the 11 enrolled accounts held an open Stader request at its window start, and step 1 checks again before the deploy. A wallet step 1 names is NOT handled by this release and its page was not tested: a request already claimed reads as money added (above), and one still open at the release enters the books at the first reading after it, a path no test covers. So a non-zero line stops the release (step 1).

Prod, in order. Steps 4 to 8 write prod and need the owner's go. In release v0.86.0 this entry ships with Apyx's and the coverage floor's, and the three run as one order: the combined pass. Its order and numbers win where they differ from the steps below, which are written as if this entry shipped alone after the coverage floor moved (the runner refuses a sweep from below 24,136,053 in this release).

  1. Before the deploy, read-only: does any enrolled wallet hold a Stader request at its window start? For every account, the manager's open-id list for the wallet at its history floor block:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    PGOPTIONS='-c default_transaction_read_only=on' psql "$DATABASE_URL" -tA -F' ' \
      -c "SELECT uid, history_floor_block FROM onchain_credit.accounts WHERE history_floor_block IS NOT NULL ORDER BY 1" |
    while read -r w b; do
      r=$(curl -s -X POST -H 'content-type: application/json' "$ETHEREUM_ARCHIVE_RPC_URL" -d \
        "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"eth_call\",\"params\":[{\"to\":\"0x9f0491b32dbce587c50c4c43ab303b06478193a7\",\"data\":\"0x7a99ab07000000000000000000000000${w:2}\"},\"$(printf '0x%x' "$b")\"]}" |
        sed -nE 's/.*"result":"0x[0-9a-f]{64}([0-9a-f]{64}).*/\1/p')
      if [[ "$r" =~ ^[0-9a-f]{64}$ ]]; then echo "$w floor=$b open_requests=$((16#${r: -8}))"; else echo "$w floor=$b read_failed"; fi
    done

    Every line reads open_requests=0 (all 11 on 2026-10-09). A read_failed line: run it again until every wallet answers. A non-zero line: stop, do not deploy, and bring the wallet to Fred (above: this release does not handle it, and what its page would show was not tested).

  2. The deploy (the release merge), and migration 137: one additive UPDATE of ETHx's registry row (exit_queue = 'stader-ethx-withdraw-queue'), safe before or after the deploy (nothing reads the column at run time). Applied by the standing runner after the deploy; check it, read-only:

    sql
    SELECT symbol, redeem_terms, redeem_networks, exit_queue
      FROM onchain_credit.portfolio_tokens
     WHERE chain_id = 1 AND address = '0xa35b1b31ce002fbf2058d22f30f95d405200a15b';
    -- ETHx|queued|{ethereum}|stader-ethx-withdraw-queue

    Migrations 133 (Renzo) and 136 (wBETH) touch other rows; the files apply in any order.

  3. The registry check, read-only:

    bash
    cd /opt/onchain-credit && ETHEREUM_RPC_URL="$(grep ^ETHEREUM_RPC_URL= .env.local | cut -d= -f2-)" \
      npm run verify:escrow-registry

    Exit 0, 10 class(es), 40 assertion(s) on this entry's own (11 class(es), 50 assertion(s) in v0.86.0, which also carries Apyx's ten), and the seven new lines read (mainnet, read from the branch on 2026-10-09: all 40 assertions matched):

    text
    ok   stader-ethx-withdraw-queue staderConfig()         0x4abef2263d5a5ed582fc9a9789a41d85b68d69db
    ok   stader-ethx-withdraw-queue getUserWithdrawManager() 0x9f0491b32dbce587c50c4c43ab303b06478193a7
    ok   stader-ethx-withdraw-queue getETHxToken()         0xa35b1b31ce002fbf2058d22f30f95d405200a15b
    ok   stader-ethx-withdraw-queue getStakePoolManager()  0xcf5ea1b38380f6af39068375516daf40ed70d299
    ok   stader-ethx-withdraw-queue staderConfig()         0x4abef2263d5a5ed582fc9a9789a41d85b68d69db
    ok   stader-ethx-withdraw-queue getProxyImplementation(address)[0x9f0491b32dbce587c50c4c43ab303b06478193a7] 0x678f0d5aac7398502b50b24b3ce67ea2dc4fc29c
    ok   stader-ethx-withdraw-queue getMinBlockDelayToFinalizeWithdrawRequest() 1800

    getProxyImplementation and getMinBlockDelayToFinalizeWithdrawRequest are report-only: a changed value prints as moved, adds a reported, not held line and still exits 0. A moved implementation means Stader upgraded the manager (two implementations since 2023, the last at block 18,360,801): read the new implementation's events, requestWithdraw, finalizeUserWithdrawalRequest and claim before going on, and re-pin it in the registry with that reading. A drift on any of the five hard lines (a redeployed manager, a new config or pool manager) holds the escrow cursor: stop before step 4 and find out why.

  4. GATED: sweep the escrow stream from the floor to its live cursor, so the new filter's history is ingested (attended; idempotent upserts, archive RPC; the other filters re-read stored rows). First read, read-only, the stored escrow rows over step 5's range, which step 5 adds to: SELECT count(*) FROM onchain_credit.raw_events WHERE chain_id = 1 AND stream = 'escrow' AND block_number BETWEEN 24136053 AND 25828233 (166,457 on prod on 2026-10-11, every class but Stader's and Apyx's). Then:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    TO=$(psql "$DATABASE_URL" -tAc "SELECT last_scanned_block FROM onchain_credit.chain_scan_cursors WHERE chain_id = 1 AND scope = 'ledger:escrow'")
    npx tsx scripts/backfill-event-ledger.ts --stream escrow --from 24136053 --to "$TO" --dry-run
    npx tsx scripts/backfill-event-ledger.ts --stream escrow --from 24136053 --to "$TO"

    Keep the sweep's output: its window lines ([backfill-ledger/escrow] [<from>,<to>] wrote N · …) give step 6's pin. Check, read-only: SELECT topic0, count(*), min(block_number) FROM onchain_credit.raw_events WHERE chain_id = 1 AND stream = 'escrow' AND address = '0x9f0491b32dbce587c50c4c43ab303b06478193a7' GROUP BY 1 returns both 0x5b2ce385… (requests) and 0xc41189bc… (claims), with min(block_number) >= 24136053. The counts are not pinned (claims can outnumber requests here, since a 2026 claim may settle a 2025 request); step 5's independently measured band judges them. Read S, the Stader rows inside step 5's range: the count above with AND address = '0x9f0491b32dbce587c50c4c43ab303b06478193a7' added.

  5. GATED: re-measure the stream's history band over the new filter set, from the second provider:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    LEDGER_VERIFY_RPC_URL=<second provider> \
      npx tsx scripts/record-ledger-backfill-band.ts --stream escrow --to 25828233 \
        --note "<date> Stader's ETHx withdrawal manager joins the escrow stream" --window 5000 --dry-run
    # then the same with --confirm in place of --dry-run

    Expect, over [24,136,053, 25,828,233], step 4's baseline plus S: 166,457 + S on this entry's own (166,457 + S + 3,364 in v0.86.0, with Apyx's rows: the combined pass, step 8). The measured count must also equal the stored count over that range after step 4; a stored count above baseline plus S means the sweep filled rows of an older class as well: stop and read them.

  6. GATED: the completion run, which judges the corpus against step 5's band and promotes the certificate, the new key included. Condition 3 is pinned to a record step 4 wrote, on both runs (why, and how to read the pin):

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    PIN=$(psql "$DATABASE_URL" -tAc "SELECT from_block FROM onchain_credit.chain_scan_ranges
      WHERE chain_id = 1 AND scope = 'ledger:escrow:backfill' AND from_block BETWEEN 24136053 AND 25188586
      ORDER BY scanned_at DESC LIMIT 1")   # read-only; 25186053 at the default 50,000-block window
    LEDGER_VERIFY_RPC_URL=<second provider> npx tsx scripts/backfill-event-ledger.ts --stream escrow --sample "$PIN"
    LEDGER_VERIFY_RPC_URL=<second provider> npx tsx scripts/backfill-event-ledger.ts --verify --stream escrow --sample "$PIN"   # read-only

    Expect 8 coverage row(s) stamped live from 24136053 on this entry's own (9 in v0.86.0, with Apyx's receipt), condition 3 pass on [<PIN>,…] and a verify PASS; event_coverage lists the manager's escrow row, live from 24136053, and the seven existing escrow rows still from 22527558. A refusal publishes nothing and names its reason; do not answer it by re-running.

    The full-depth figures this entry was first written with no longer apply: a sweep from 22,527,558 (2,983 requests and 2,796 claims, the first at block 22,527,614) and a band of 319,220 over [22,527,558, 25,828,233]. The coverage floor moves in the same release and the runner then refuses --from 22527558. Stader requests made before 2026 are not ingested; none is read by any wallet's history, whose window starts in 2026, and an open one is still valued from the manager's own state.

  7. GATED: after step 6, take the wallet list (read-only), then re-derive those wallets from their floor, and only those: every enrolled wallet that ever moved ETHx (every direct request sends ETHx to the manager), and every wallet a swept request names as its owner (the hsETH route moves no ETHx of the holder's):

    sql
    -- read-only: the wallet list for steps 7 and 8
    WITH w AS (SELECT uid, '0x000000000000000000000000' || substr(uid, 3) AS t FROM onchain_credit.accounts)
    SELECT w.uid
      FROM w
     WHERE EXISTS (SELECT 1 FROM onchain_credit.raw_events e
                    WHERE e.chain_id = 1 AND e.stream = 'wallet-token'
                      AND e.address = '0xa35b1b31ce002fbf2058d22f30f95d405200a15b'
                      AND e.topic0 = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'
                      AND (e.topic1 = w.t OR e.topic2 = w.t))
        OR EXISTS (SELECT 1 FROM onchain_credit.raw_events e
                    WHERE e.chain_id = 1 AND e.stream = 'escrow'
                      AND e.address = '0x9f0491b32dbce587c50c4c43ab303b06478193a7'
                      AND e.topic0 = '0x5b2ce38527d3f69f0bf03c1a363829ba12d09551f8778a9b0b9e1285ec19721a'
                      AND substr(e.data, 27, 40) = substr(w.uid, 3))
     ORDER BY 1;

    Zero rows means steps 7 and 8 have nothing to do (2026-10-09: no enrolled wallet moved ETHx inside its window; the prod test wallet 0xdd647ce1…c737 made three requests in 2026-08, all claimed before its window). Otherwise queue one whole-window rederive per listed wallet with the runbook's insert and read it done from portfolio_derive_jobs. Never before step 6: a re-derived wallet with a Stader movement then requires the missing certificate and withholds.

  8. Check, read-only, per re-derived wallet:

    sql
    SELECT block_number, venue, position_key, kind, amount_raw, consideration_raw, to_balance, link_id, meta->>'withheld' AS withheld
      FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND wallet = '<wallet>' AND link_kind = 'escrow'
       AND (position_key LIKE 'escrow:stader-ethx-withdraw-queue:%' OR meta->>'escrowClass' = 'stader-ethx-withdraw-queue')
     ORDER BY block_number, log_index, seq;

    Every request is one link_id (esc:1:0x9f04…93a7:<request id>) holding an internal_out on wallet:token:0xa35b…a15b (its consideration_raw the ticket's ether value) and an internal_in on escrow:stader-ethx-withdraw-queue:<id> (a transfer_in for an hsETH-route request), and at its claim an internal_out on the ticket (its to_balance 0) beside the ether internal_in. No transfer_out of ETHx to the manager and no transfer_in of a claim's ether remain, except a claim of a pre-window ticket no reading held (above). Zero held-back rows (withheld) for the class, the reconciler's line for the wallet (npx tsx scripts/ops/reconcile-ledger.ts --wallet <wallet>) clean, and on /portfolio an open request reads as an In settlement ETHx row with a value and a Dislocation P&L figure. Then the issue's shared-code regression check: the two prod test wallets (0xdd647ce1…c737, 0xd1a557fe…6e09) still build their history completely (derive cursor present, zero held-back rows, their In settlement rows valued).

  9. Record executed: with the date, step 1's lines, step 3's output, step 6's coverage lines and step 8's rows.

Staging. Steps 1, 3 and 8's queries are read-only and safe there; the nightly reseed restores prod's raw_events and event_coverage, so a staging sweep is undone by the next reseed and proves nothing about prod (staging's data is a reseed).

Rollback. A code rollback does not roll back the database. The previous release reads no Stader leg, so a wallet holding the class's rows is refused by its escrow universe until it is re-derived under the previous code (which books the ETHx sent and the ether received as transfers again). The ingested Stader logs, the manager's certificate row and migration 137's exit_queue value are inert under the previous code.

Step-anchored 24h APY for weETH, ezETH and fxSAVE (migration 135, #680 PR): prod steps, in order ​

  • belongs to: the step-anchored window PR (branch fix/step-anchored-apy-680), migration 135
  • executed: 2026-10-09
  • run record: (v0.85.0, release PR #1097, merge b520bbdb, deploy run 37970504638 green; the app restarted on 0.85.0 at 18:03:42Z; migrate.sh at 18:04Z applied 132 to 136, five files). Step 2: step_ts|timestamp with time zone. Step 3: the 18:00 cron tick ran on the previous release (the app restarted at 18:03:42Z), so the first tick on this release was the hand refresh-assets.ts of the wBETH entry's step 3 (18:37Z, rewriting the 18:00 window); the 18:50Z portfolio tick also passed before step 4. Rows: ezETH|2026-10-09 18:00|0.0525|step_ts 2026-10-09 02:16:11, fxSAVE|…|9.2657|12:50:35, weETH|…|2.3067|17:50:11; 0 step-fail and 0 step-ts-skip lines. ezETH's 0.05% is true: its rate has stalled since 2026-10-08 (share rate 1.0872738 to 1.0872798 in two days; the fixed window read 0.0475% on every tick since). Step 4 dry run (19:03Z): per token 120 rows, 119 to write, 1 already current, 0 step search(es) failed; weETH stddev 0.2083% → 0.0387% (mean 2.3414% → 2.3425%), ezETH 2.6989% → 1.1481% (2.5911% → 2.0749%), fxSAVE 1.5692% → 0.7859% (6.6122% → 6.5878%). --write (19:04Z to 19:06Z): the same lines, wrote 357 row(s), exit 0, no failed row, so no re-run. Step 5: the prod deploy re-run at 19:06Z (the carry listings' step 7) re-prerendered after the write.

What it changes for a user, in one line: the 24h APY of weETH, ezETH and fxSAVE stops zigzagging every six hours (weETH 2.04% / 2.45% around a true 2.35%) wherever it is shown: the 24h APY column on /portfolio, their collateral leg on /carries (its Carry range band narrows), and their yield history on /asset-profiles. No other token's reading moves.

  1. The deploy (merge staging into main). Order does not matter. The refresher writes step_ts in its own best-effort UPDATE after the snapshot INSERT, so a tick between the deploy and the migration writes every row as before and only logs [token-yields/step-ts-skip] for the three tokens; no app code reads the column.

  2. Migration 135, by the standing runner (additive, no runner tag):

    bash
    cd /opt/onchain-credit && scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)"
    sudo -u postgres psql -d creddit -At -c "SELECT column_name, data_type FROM information_schema.columns WHERE table_schema = 'onchain_credit' AND table_name = 'token_yield_apy' AND column_name = 'step_ts'"

    Expect step_ts|timestamp with time zone.

  3. Wait for one 6h tick, then check the live path wrote step-anchored rows for all three:

    bash
    sudo -u postgres psql -d creddit -At -c "SELECT token_symbol, snapshot_ts, round(supply_apy * 100, 4), step_ts FROM onchain_credit.token_yield_apy WHERE token_address IN ('0xcd5fe23c85820f7b72d0926fc9b05b43e359b7ee', '0xbf5495efe5db9ce00f80364c8b423567e58d2110', '0x7743e50f534a7f9f1791dde7dcd89f7783eefc39') AND snapshot_ts = (SELECT max(snapshot_ts) FROM onchain_credit.token_yield_apy) ORDER BY token_symbol COLLATE \"C\""
    grep -c 'token-yields/step-fail' /tmp/onchain-credit-cron/onchain-credit-refresh-assets.log

    Expect three rows, each with a step_ts within a few hours before its snapshot_ts (within 7 days at most) and a plausible APY (weETH ~2.3%), and no new step-fail lines. A NULLsupply_apy with a step-fail line is a failed archive read on that tick, not a wrong reading.

  4. GATED: re-derive the stored window (a prod write; needs Fred's explicit go). Dry run first:

    bash
    /opt/onchain-credit/scripts/run-cron.sh backfill-step-anchored-apy.ts --dry-run

    Expect, per token, 0 step search(es) failed and stddev falling roughly as it did on the 2026-10-09 read-only verification of the same 30 days: weETH 0.21 → ~0.04, ezETH 2.72 → ~1.2, fxSAVE 1.55 → ~0.75 (fxSAVE's harvests genuinely pay unevenly, so only the quantisation part of its zigzag goes). A weETH figure far above ~0.05 means the step detection is wrong: stop, do not write. Then:

    bash
    /opt/onchain-credit/scripts/run-cron.sh backfill-step-anchored-apy.ts --write

    A row whose search failed is left as stored and the exit code is non-zero; re-run the same command (idempotent) until it reports none.

  5. Re-render: /asset-profiles and /carries are ISR pages (see the ISR caveat); re-run the deploy or wait for the window.

  6. Record the run here: the date in executed:, the dry run's per-token lines and the write count.

Rollback. The column is additive and unread, so it is never reverted. A code rollback with 135 applied writes the fixed 24h window again from the next tick (and the gap repaint resumes for the three tokens); the re-derived history stays a true realised reading between two real rate steps.

The event ledger's coverage floor moves up to 2026-01-01 (migration 138, "plan A"): prod steps, in order ​

  • belongs to: the coverage-floor release (branch chore/ledger-floor-2026), migration 138 (additive: the declared address count on a recorded band)
  • executed: 2026-10-12
  • run record: (v0.86.0, release PR #1114, merge 5da805f7, deploy run green 21:28:17Z to 21:29:29Z on 2026-10-11; migrate.sh applied 137, 138 and 139, 3 applied.) Step 1: declared_addresses|integer|YES. Step 2: the deploy restarted the ingester at 21:29:25Z on the new code; 0 cycle error in its last 200 lines, scanned lines on every stream, no catch-up line at all. Step 3, read-only first (22:02Z): 648 live of 648 keys, 792,610 stored rows over [24136053,25840566]. The dry run (22:02:49Z to 22:07:42Z, Tenderly; independence established against the sweep's Alchemy receipts): measured 784817 claimed row(s) (784817 raw log(s), 1705 chunk(s)) over [24136053,25840566] across 639 declared address(es). Stopped there, not confirmed: N and D differ from the step's expectation as it then read (N = the stored count, D = the keys). Read-only reading of the gap: nine of the 648 erc4626 coverage keys are no longer in the stream's declared set (listed vaults plus the registry's wallet tokens): all nine are registry rows that migration 105 (the coverage rule, applied on prod 2026-09-17 13:22Z) retired, and a retired row leaves every set built from the registry, this one included. Eight are dollar tokens that never emit an ERC-4626 event and hold no row; the ninth, stUSDS (0x99cd4ec3…eeb9), holds 7,793 stored rows in the range (blocks 24,137,593 to 25,840,181; its last stored row is at 25,997,192, the day of the retirement). No tracked wallet holds stUSDS at its window start or now (read on chain, 2026-10-11). 792,610 minus 7,793 is 784,817, so the measurement equals the stored rows on today's declared set exactly: no hole and no decode gap, the difference is that retired address's history. Recording 784,817 as it stands would fail step 4: condition 1 counts every stored row of the stream in the range (792,610), and with 639 declared addresses the ceiling is 784,817. The recorder cannot record 792,610 (it measures today's declared set). Fred's decision, 2026-10-12: keep the stored events (plan A) and fix the gate. Condition 1 now counts only the rows a band measured: commit 1494b3a2 on staging, migration 142 (its entry, which also records the pre-check on the nine stale coverage rows). Steps 3 and 4 re-run after that release, with the figures this entry's steps now state (measured 784,817 across 639, equal to the stored rows on the declared set; condition 1 exact with 7793 stored row(s) on addresses in neither, not counted). Step 4 has not run: it needs step 3's band.
  • run record: (v0.87.0, its combined pass step 15, after step 10's escrow completion; merge 1284e4c7, 2026-10-12.) Step 4's refresh (Fred's approval, erc4626 only): F 25827558, T 25840566 (scanned_at 2026-08-26 before); dry run plan [25827558,25840566] · 1/1 window(s) this run · bottom: explicit --from (overrides the resume cursor), 640 certificate key(s); the run [25827558,25840566] wrote 0, range retained as raw evidence only, 0 new row(s), the record's scanned_at now 17:45:03Z. Step 3, read-only first: 640 live of 640, 784,903 stored rows on the declared set (792,696 in all). Dry run 17:45:13Z to 17:52:32Z (Tenderly; independence established against the sweep's Alchemy receipts): measured 784903 claimed row(s) (784903 raw log(s), 1705 chunk(s)) over [24136053,25840566] across 640 declared address(es), would record erc4626=784903 … · address list: erc4626 640 address(es); --confirm 17:56:47Z to 18:02:05Z: recorded erc4626=784903 over [24136053,25840566], superseding 1,254,735 over [22527558,25840566]. Step 4: the first two attempts of the every-stream --verify --window 1000 (18:03Z, 18:07Z) ended fatal: canceling statement due to statement timeout after four and five streams (the app role's 30 s statement_timeout; the same stream alone passed); the third, with PGOPTIONS="-c statement_timeout=600s -c default_transaction_read_only=on" (18:12:17Z to 18:20:58Z), ran all 13: header floor 24136053; conditions 1 to 4 pass on morpho, aave-pool, spark-pool, aave-token, spark-token, fluid-operate, fluid-nft, fluid-dex, pendle-router and escrow (176760 row(s) over [24136053,25828233] vs [176760,176760], 0 stored row(s) on addresses in neither, condition 3 on [24686053,24736052], verify PASS · run c1e832d0591d); condition 3 MISS with 1, 2 and 4 passing, the stale-record effect, recorded as read and not refreshed, on transfers (5206386 row(s) over [22527558,25654266] vs [5062171,6962171], 64 receipt(s), no gap, MISS on [23527558,23577557], 821/821 declared address(es) live; an earlier attempt's draw [22627558,22677557] passed), wallet-token (5020 row(s) over [22527558,25844836] vs [1973,24473], 3442 receipt(s), no gap, MISS on [22827558,22877557], 15/15 declared address(es) live from the floor, with the note that 0xef08…07c5 is not enrolled) and erc4626 (784903 row(s) over [24136053,25840566] vs [784903,784903] · … (ceiling sized off 640 declared address(es) vs 640 measured, 0 declared since) (counted on the measured addresses plus those declared since; 7793 stored row(s) on addresses in neither, not counted), MISS on [25627558,25677557], 640/640). The pinned run --verify --stream erc4626 --window 1000 --sample 25827558: conditions 1 to 4 pass, condition 3 on [25827558,25840566] · pinned by --sample, one of 35 current sweep record(s), verify PASS · run 61f3afe4e7c7.

What it changes for a user, in one line: nothing visible. No page, figure or chart moves for any wallet; what changes is how deep the event history has to reach before a newly onboarded venue, escrow queue or token can be trusted, which drops from 2025-05-21 to 2026-01-01.

What it does, and what it leaves.

  • Code plus one additive column. The coverage floor every protocol-wide stream sweeps from, certifies to and is checked against becomes the derivation floor, block 24,136,053 (2026-01-01), instead of 22,527,558 (2025-05-21) (the floor). The ingester starts a new address's catch-up there and stops resolving 2025-05-21 to a block; the stream runner sweeps from there and refuses a --from below it; the band recorder measures from there.
  • Nothing is deleted or re-measured. Every stored row, scan receipt, coverage row and band from 22,527,558 stays, and stays valid: each rule reads "covered from at or below the floor", so the thirteen '*' markers and the per-address rows reading 22527558 keep passing as they are. --verify keeps judging each pre-2026 campaign over the range it was measured over.
  • No served number moves, measured read-only on prod on 2026-10-11: the 12 accounts' history floors run from block 25,900,227 to 25,943,261 (none below 2026-01-01); the 10 wallets' derived movements start at 25,900,227 (zero below 2026-01-01); zero coverage rows start between the two floors (the 13 '*' markers and all 1,699 protocol-wide per-address rows start at 22,527,558, each wallet-token row at its wallet's own floor and each native-eth row at the feed's first block, 26.1M), so every certificate check gives the same answer at either floor; every coverage row is live, so no catch-up is in flight to change course; and the market impairment pass's cursor is at the tip (26,167,702), far above both floors. The PT rows' pre-window fills read the kept 2025 router rows exactly as before.
  • The historical acceptance gate passes on all 13 streams afterwards (conditions 1, 2 and 4; the sampled re-check, condition 3, needs a pinned record on erc4626, and on escrow before v0.87.0, step 4), which it did not before: two streams failed it for reasons this release fixes. erc4626's recorded band (1,254,735 rows, measured over 546 vaults) was outgrown by the ~100 vaults listed since, each caught up inside its range (1,455,064 stored); the gate now widens a growing stream's ceiling per vault declared since the measurement (migration 138 records the count; the floor stays the measured number), and step 3 re-measures the band once so it carries that count. wallet-token's per-wallet certificate was judged at the coverage floor although each wallet's history is collected from its own floor, and its named anchor was a transfer between two wallets one of which (0xef08…) has since been wiped; each wallet is now judged at its own floor, and the anchor runs only while both of its wallets are enrolled and otherwise says so.
  • Any later escrow class or stream sweeps from 24,136,053. A pending release step written before this one that sweeps --from 22527558 is refused after this deploy; Stader's entry is written in its floor-moved form.
  • The two widened-topic coverage resets are not owed again (Pool streams, Fluid streams): prod's stored history already holds every widened topic from 2025-05 (Supply from 22,527,559, NewPositionMinted from 22,528,749, LogAbsorb from 22,755,521), which is what those repairs earn. Repeating either now would re-certify from 24,136,053 and leave that stream's frozen 2025 evidence unable to pass.

In release v0.86.0 this entry ships with Stader's and Apyx's, and the three run as one order: the combined pass. Its order and numbers win where they differ from the steps below. Steps 3 and 4 did not finish there: they wait for migration 142 and run in v0.87.0, after that release's escrow completion, as step 15 of v0.87.0's combined pass, whose numbers win.

  1. GATED: apply migration 138 (additive, nullable; auto-applied on staging):

    bash
    cd /opt/onchain-credit && scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)"

    migrate.sh applies EVERY pending file, so in v0.86.0, which also carries Stader's and Apyx's entries, this run also applies their 137 and 139 (keep Stader's step-2 check and Apyx's step-1 check). Expect 138-ledger-band-declared-addresses.sql applied. Read-only check: SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema = 'onchain_credit' AND table_name = 'ledger_backfill_acceptance_bands' AND column_name = 'declared_addresses' returns declared_addresses|integer|YES. Until it lands the gate reads every band without the count (exactly, as before) and the recorder in step 3 refuses to write, so apply it first.

  2. Confirm the ingester restarted on the new code and runs a clean cycle. The deploy restarts creddit-event-ingester itself (the deploy restarts the ingester); restart it by hand only if the deploy run says it did not:

    bash
    pm2 restart creddit-event-ingester --update-env   # ONLY if the deploy run reported no restart
    pm2 logs creddit-event-ingester --lines 200 --nostream | grep -c 'cycle error'   # expect 0
    pm2 logs creddit-event-ingester --lines 200 --nostream | grep -E 'scanned|caught up|catch-up' | tail -20

    Expect per-stream scanned lines, no cycle error, and no catch-up line naming a floor below 24136053 (with every coverage row live there should be no catch-up line at all).

  3. GATED: re-measure erc4626's band from the second provider. Runs only after migration 142's release is deployed and 142 applied (the v0.86.0 run stopped at this step's dry run: the measurement covers today's declared set, while the gate before 142 counted every stored row, the 7,793 of retired stUSDS included). A prod write: one appended band row; attended; a full eth_getLogs walk of ~1.7M blocks across ~650 addresses, so expect hours at --window 1000). The range is [24,136,053, 25,840,566], deliberately: the recorder measures from the coverage floor, which is the range every vault listed from now on is caught up over, so the band and its future growth describe the same blocks; it is half the walk of the old range; the stream's anchors are presence checks that hold over it; and its receipts are contiguous over it (read-only on prod, 2026-10-11). The top is the stream's backfill handoff (ledger:erc4626:backfill = 25,840,566), the highest --to the gate accepts.

    First, read-only, the two things the measurement has to agree with:

    sql
    SELECT count(*) FILTER (WHERE status = 'live') AS live, count(*) AS keys
      FROM onchain_credit.event_coverage WHERE chain_id = 1 AND stream = 'erc4626' AND address <> '*';
    SELECT count(*) FROM onchain_credit.raw_events
     WHERE chain_id = 1 AND stream = 'erc4626' AND block_number BETWEEN 24136053 AND 25840566;

    Every key must be live (a vault mid-catch-up has rows the measurement counts and the corpus does not yet hold: wait for its caught up line). On 2026-10-11: 648 live of 648, and 792,610 rows, nine of the keys being registry rows migration 105 retired (stUSDS and eight dollar tokens; 142's entry). On 2026-10-12 those nine rows were removed and RockawayX Tori (0x3bd9adae…9478, listed that day) caught up: 640 live of 640, and 792,696 rows, so every key is declared. The count the measurement must equal is the stored rows on the declared set, which is every key (the nine addresses stay excluded below in case a row for one comes back):

    sql
    SELECT count(*) FROM onchain_credit.raw_events
     WHERE chain_id = 1 AND stream = 'erc4626' AND block_number BETWEEN 24136053 AND 25840566
       AND address IN (SELECT address FROM onchain_credit.event_coverage
                        WHERE chain_id = 1 AND stream = 'erc4626' AND address <> '*')
       AND address NOT IN ('0x99cd4ec3f88a45940936f469e4bb72a2a701eeb9', '0x66a1e37c9b0eaddca17d3662d6c05f4decf3e110',
                           '0xa0d69e286b938e21cbf7e51d71f6a4c8918f482f', '0x8d0d000ee44948fc98c9b98a4fa4921476f08b0d',
                           '0x73a15fed60bf67631dc6cd7bc5b6e8da8190acf5', '0x056fd409e1d7a124bd7017459dfea2f387b6d5cd',
                           '0x0000000000085d4780b73119b644ae5ecd22b376', '0x0c10bf8fcb7bf5412187a595ab97a3609160b5c6',
                           '0xc5f0f7b66764f6ec8c8dff7ba683102295e16409');

    784,903 on 2026-10-12 (792,696 less stUSDS's 7,793; the other eight hold no row). Then:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    LEDGER_VERIFY_RPC_URL=<second provider> \
      npx tsx scripts/record-ledger-backfill-band.ts --stream erc4626 --to 25840566 \
        --note "<date> re-measure from the 2026-01-01 floor across the grown vault set" --window 1000 --dry-run
    # then the same with --confirm in place of --dry-run

    Read three lines before confirming. independence established against the sweep's own scan receipts (eth-mainnet.g.alchemy.com): the second provider must be any host but the one named there (the recorder refuses otherwise). measured N claimed row(s) … over [24136053,25840566] across D declared address(es): D is 640 (every key, on 2026-10-12), N equals the declared-set count above (784,903 on 2026-10-12, plus whatever vaults listed since added); a different N is a hole or a decode gap, so stop and find it rather than confirm. The dry run's would record erc4626=N … · address list: erc4626 D address(es) repeats both (no address list means 142 is not applied: stop). --confirm then prints recorded erc4626=N over [24136053,25840566].

  4. Read-only: the historical acceptance gate over every stream. Only after the escrow completion of the release that runs it (v0.87.0: its combined pass, step 10, then step 15). A release that adds escrow classes declares their certificate keys from its deploy, and the keys have no coverage row until its completion run stamps them, so before that escrow's condition 4 misses (2 declared address(es) not live from the floor: 0x…, 0x…, the queue's and the redeemer's keys, between v0.87.0's deploy and its step 10). From v0.87.0 (commit 01c371f3) escrow needs no pin: condition 3 draws only the newest record per block range (the pin section), so escrow runs with every other stream, and only erc4626 runs again on its own, pinned to the record this step's refresh below rewrote:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    LEDGER_VERIFY_RPC_URL=<second provider> npx tsx scripts/backfill-event-ledger.ts --verify --window 1000
    # erc4626, pinned to the record refreshed below (F)
    LEDGER_VERIFY_RPC_URL=<second provider> npx tsx scripts/backfill-event-ledger.ts --verify --stream erc4626 --window 1000 --sample "$F"

    Both write nothing (each re-scans one stored sweep record per stream on the second provider). The header line reads floor 24136053. Every range reads [22527558, …] except two: erc4626's, [24136053,25840566], whose row count reads against [N, N + 7,000 × vaults declared since] and is counted on the measured addresses plus those declared since: with no listing since step 3, 784903 row(s) over [24136053,25840566] vs [784903,784903] · evidence independent-chain-scan (ceiling sized off 640 declared address(es) vs 640 measured, 0 declared since) (counted on the measured addresses plus those declared since; 7793 stored row(s) on addresses in neither, not counted), the 7,793 being stUSDS's kept history; and escrow's, [24136053,25828233], the band v0.87.0's escrow pass recorded (its combined pass, step 9): 176760 row(s) … vs [176760,176760], with 0 stored row(s) on addresses in neither. wallet-token's condition 4 reads N/N declared address(es) live from the floor (a wallet's own, on wallet-token), one per enrolled wallet (15 on 2026-10-12), with the note that 0xef08…07c5 is not enrolled. The stored counts behind the other ten (every stream but erc4626, escrow and wallet-token) were read on prod on 2026-10-11 and sit on or inside their bands, with contiguous records.

    What must pass: all four conditions on the other streams, escrow included, in the first run, except condition 3 on three streams whose sweep records predate today's declared set: erc4626 (its condition 3 passes in the pinned run instead: verify PASS, condition 3 on [F,…]), wallet-token (its records were written on 2026-08-27 over the wallets enrolled then; every account was wiped on 2026-10-03, and only 293 of the 4,495 stored rows in its range involve today's 15 wallets) and transfers (records from 2026-08-28; about 100 addresses listed since, RockawayX Tori among them). On those three a condition 3 MISS, with conditions 1, 2 and 4 passing, is the stale-record effect below, not a hole, and the first run then ends without the closing every stream passed all four conditions. Record the wallet-token and transfers lines as they read, and do not refresh them: a one-window re-sweep of wallet-token over today's wallets would write their transfers from before their own floors (a non-zero wrote), and Fred's approval covers the erc4626 refresh only. Any other miss, an escrow one included: stop and read its verdict line. One more reads differently: a vault listed between step 3 and this step, larger than 7,000 rows over the range, fails erc4626's condition 1 ABOVE the ceiling, which means re-measure (step 3 again), not a hole. From here on erc4626 is re-measured on the runbook's rule (a failure above the ceiling, or 50 vaults declared since the measurement).

    erc4626's condition 3 can miss without a hole (found in the v0.86.0 review; not measured on prod). Its sweep records were written in 2026-08 over the 546 vaults declared then. The ~100 vaults listed since were caught up by the ingester, which writes rows and coverage but no sweep record, and step 3's re-measure writes none either, so no stored erc4626 record was taken over today's vault set (648 on 2026-10-11). Re-scanned with today's set, a record mismatches whenever a vault listed since logged anything inside its window, which most 2026 windows will hold. The newest-per-range rule (from v0.87.0, escrow's pin section) does not change this: these records are the newest of their blocks, just taken over a smaller vault set. Pinning --sample to an existing record does not avoid it: none is guaranteed to reproduce, and which would cannot be told from the stored data (a vault dropped from the set since breaks a record too). The safe form is to refresh one record over today's vault set first and pin to it, a GATED prod write that changes nothing anyone reads:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    # read-only: the newest erc4626 sweep record inside the band, above the floor
    psql "$DATABASE_URL" -tA -F' ' -c "SELECT from_block, to_block FROM onchain_credit.chain_scan_ranges
      WHERE chain_id = 1 AND scope = 'ledger:erc4626:backfill' AND from_block > 24136053 AND to_block <= 25840566
      ORDER BY from_block DESC LIMIT 1"
    F=<from_block>; T=<to_block>
    # GATED: re-sweep exactly that range, as one window
    npx tsx scripts/backfill-event-ledger.ts --stream erc4626 --from "$F" --to "$T" --window $((T - F + 1)) --dry-run
    npx tsx scripts/backfill-event-ledger.ts --stream erc4626 --from "$F" --to "$T" --window $((T - F + 1))
    # read-only: condition 3 pinned to the refreshed record
    LEDGER_VERIFY_RPC_URL=<second provider> npx tsx scripts/backfill-event-ledger.ts --verify --stream erc4626 --window 1000 --sample "$F"

    Expect the plan line plan [F,T] · 1/1 window(s) this run · bottom: explicit --from (overrides the resume cursor), then [F,T] wrote 0 · … and range retained as raw evidence only, then the pinned run's verify PASS. The re-sweep rewrites the one record at F over today's vaults (same key and range, so condition 2 is unchanged); rows already stored are skipped; every coverage row keeps its range and stays live; the backfill cursor only moves up, so it stays; nothing is promoted. A non-zero wrote means the stored history lacked rows in that window: stop and find why. Run it before step 3 when you can, so step 3 measures the same corpus. On 2026-10-12 the record is [25827558,25840566] (read on prod), and Fred approved the write for v0.87.0 (its combined pass, step 15). If Fred declines the write, record erc4626's condition 3 line as it reads, with this paragraph as the reason. The same applies to any stream whose declared set grew or changed after its sweep (transfers grows with every listed reserve, vault or PT; wallet-token follows the enrolled wallets): a condition 3 miss there, with the other three passing, is this effect. A refresh and pin would clear it, but in v0.87.0 neither is refreshed: record the line as it reads (above).

  5. Record executed: with the date, step 1's line, step 2's counts, step 3's measured and recorded lines and step 4's per-stream verdict lines.

Staging. Migration 138 auto-applies there. Steps 2 and 3 do not apply (staging has no ingester, and a band recorded there is wiped by the nightly reseed); step 4 is read-only but measures staging's reseeded copy, which proves nothing about prod.

Rollback. A code rollback restores the 2025-05-21 floor. Migration 138's column and step 3's band row are inert under the previous code, except that the previous gate refuses the new band's range (it accepts only bands starting at 22,527,558), so erc4626's verify reads red again until a forward release; nothing served reads either. Beyond that the release writes nothing. What can be written after the deploy is coverage stamped from 24,136,053: a new address's catch-up, or a stream or escrow class onboarded since. The previous code reads such a row as short of its floor. For a per-address row that fails only the backfill verification (the served completeness check asks for 2026-01-01 under both releases), but a NEW stream's '*' marker reads as not rolled out, and a marker-governed stream with no marker has its requirement dropped rather than withheld. So roll back before anything new is onboarded; after that, a rollback also needs that stream deferred (DEFERRED_SCOPES) in the rolled-back code. The same refusal hits any escrow band recorded from 24,136,053 after the deploy (Stader's floor-moved step 5 is one): under the previous code escrow's --verify and promotion stay refused until a band is re-measured from 22,527,558, which first needs the new class swept from 22,527,558.

Repair, after this release. The legacy streams are judged over [22527558, …], but the runner refuses a --from below 24,136,053, so a hole ever found in the 2025 part of a legacy range cannot be swept closed; it is cleared by re-banding that stream from the new floor instead (for aave-pool and the Aave token pair, with their 2025 anchors restated for 2026 first).

sUSDat joins the USD book (migration 141, #1087): prod steps, in order ​

  • belongs to: sUSDat's registry row (branch oc-1087-usd-book-preferred, PR #1115), migration 141. Ships to prod in the SAME release as the Saturn queue (PR #1113, migration 140): see "One release" below
  • executed: 2026-10-12
  • run record: (v0.87.0, release PR #1126, merge 1284e4c7 at 17:10:33Z on 2026-10-12, deploy run 38282474222 green 17:10:41Z to 17:11:55Z: app, ingester and worker restarted 17:11:53Z to 17:11:55Z, health 200, box on 0.87.0; 141 by hand at 17:10:13Z before the merge; one migrate.sh at 17:12:34Z to 17:12:41Z: 5 applied (140, 142, 143, 144 and #1124's 145), 144 total on disk; run as the combined pass.) Step 1 (17:10:13Z, from /opt/onchain-credit-staging at 1cea5bc9, status --porcelain -- scripts/sql empty): applied, the row reads sUSDat|USD|variable_rate|market|dune_tape|0x23238f20b894f29041f48d88ee91131c395aaa71|0xd166337499e176bbc38a1fbd113ab144e5bd2df7|getter|{"kind": "erc4626", "divisorPow10": 6}. Step 2 (plan, read-only): 0x1929d726…f45a … 88 reading(s) would restate EXCLUDED -> USD, 2026-09-05 00:00Z -> 2026-10-08 08:29Z, 0x5bc81274…04c2 … 26 reading(s) … 2026-09-13 00:00Z -> 2026-10-07 06:00Z; 114 reading(s) to restate, 0 held back, 2 carried copies; no other asset. Step 3: merged 20 s later; the deploy restarted all three at 17:11:53Z to 17:11:55Z. The new worker's first pass (17:11:56Z): [restate] done: 1 asset(s) widened, 2 wallet(s) visited, 114 reading(s) restated, 0 held back, 2 carried copies restated, 2 rederive job(s) queued (#2262 and #2263, both done). Step 4 (the 18:00Z tick): sUSDat|2026-10-12 18:00|1.045592|||26178045 (supply_apy and apy_30d NULL), no [token-yields/fail] … sUSDat line. Step 5: plan 181 boundaries; sUSDat: 181 row(s) written in 4 statement(s), 0 kept, 0 failed … share_rate 1.004057 .. 1.044002, every row with both APYs NULL; the second --execute: nothing to write. Step 6: USD|114 (no EXCLUDED sUSDat reading left); the reconciler book-overlays=0 for 0x1929d726…f45a and 0x5bc81274…04c2 (both exit 0). The next carry-discovery run and /portfolio were not looked at (no browser check was approved).

What it changes for a user, in one line: a wallet holding sUSDat sees it in the USD view under Variable rate assets, where until now it showed in the All view only. Its MTM PnL still follows sUSDat's market price, and its Accrual only PnL follows the value per share Saturn reports, so a fall in sUSDat's backing shows there too. Its 24h APY stays a dash. A USDC or AUSD loan against sUSDat moves from Cross-currency borrowing to Carry trades, and a Pendle PT over sUSDat moves into the USD view with it.

Why. Fred's ruling of 2026-10-11: a dollar token backed by preferred stock is fixed income, not a currency bet, so it belongs in the dollar book. apyUSD falls under the same ruling but is NOT in this release. Its underlying apxUSD has no on-chain redemption value (it redeems by permission at a basket value and has traded at $0.78 to $0.94), so there is no issuer figure for its Accrual only PnL to follow. That question is open with Fred. (2026-10-12: the premise was wrong. Apyx publishes apxUSD's Redemption Value on chain, and 143's entry books both rows USD on it.)

One release with the Saturn queue (#1113). Booked USD without the queue model, an open sUSDat redemption takes the unmodelled-exit shape inside the USD view: its value is missing from the Net asset value card while it waits, and the payout lands as money added on MTM PnL and Accrual only PnL. The 2026-10-09 census counted about 90 wallets with 104 open requests, about 1.58M. Today those holdings sit in the All view, which states no return. So 141 and 140 reach prod in one release, never 141 alone; if they ever must be split, the exposure above is Fred's to accept first. Merging them to staging in either order is fine. In that release, this entry's steps 1 and 2 come before the merge, and the Saturn entry's steps keep their places (its step 0 before the merge too).

What it does, and what it leaves.

  • Code plus one additive migration (141: one UPDATE of sUSDat's row: book, underlying_address, rate_source, rate_kind, rate_getter). Its price path does not change (market, its own tape).
  • Migration 141 is applied by hand BEFORE the merge (the 119 and 123 pattern). sUSDat's row already exists, so the database's row wins over the compiled seed. The app (onchain-credit) that prod runs at step 1 (v0.86.0) reads the registry once, at start; from v0.87.0 (commit 3357d4f4) the app also re-reads it in the background every five minutes. Either way it is the deploy's restart that loads 141 into it at once (the deploy's restarts); applied first, the new row is what it loads. The event ingester and the ledger worker re-read the registry every five minutes since 2026-10-12 (no restart for registry rows), so they take it within five minutes whenever it lands, and a worker reload that changed it starts the restatement pass. The cron jobs (the yields refresher, the portfolio tick) start fresh each run and need nothing.
  • Between step 1 and the deploy (keep it to minutes: merge straight after step 2), the running previous release's app books sUSDat USD on each request but has no rate getter for it, so its Accrual only PnL figure for sUSDat holdings is withheld on reads. A previous release that loads the registry once (v0.86.0 and earlier) holds the restatement in its worker (it sees a stale registry) and its ingester writes new sUSDat readings EXCLUDED, which the restatement picks up after the deploy; one that re-reads it restates within five minutes under its own code, which values sUSDat the same way. Nothing is written wrong.
  • The worker restates existing wallets' sUSDat history by itself (the procedure): readings stored EXCLUDED are restated into the USD book from its first turn after the deploy, a few wallets per turn, and each wallet's rederive is queued. Merging the release is the go for that write. Never run restate-covered-readings.ts --execute by hand in this release.
  • The loan reclassification (Cross-currency borrowing to Carry trades) is read time: it shows from the deploy, before any restatement.
  • sUSDat's rate does not answer while STRC, which it holds, has no price (its convertToAssets reverts: blocks 26,110,049 to 26,110,609, 2026-10-03 06:34Z to 08:27Z, the one stretch measured). A reading at such a block falls back to the six-hourly series, which the yields refresher writes from this release on and step 5 fills behind it. Without the series, the restatement holds that reading back (no redemption rate at its block) and a writer skips its leg.
  • The series stores the share rate only. sUSDat's value per share is a mark of the STRC it holds, not an accrual index (day on day it annualises to anything from −68% to +1,382%), so its rows leave supply_apy and apy_30d NULL (a rate-only token; one list in src/data/rate-only-tokens.ts since 2026-10-21). No run rate counts it. (The 24h APY cell printed the N/A chip, not a dash, until 2026-10-21, when the portfolio API began stating that the rate is unquoted by design.) A quoted rate for sUSDat (Saturn's published yield, say) is a separate decision for Fred.
  • sUSDat is held out of carry discovery (Fred, 2026-10-12). A collateral counts as modellable once it has a row at the newest six-hourly snapshot, and sUSDat gains one with this release, but that row carries no APY, and sUSDat's 24h implied yield is noise. So every venue's discovery (Morpho, Aave e-mode, Fluid) drops it from its yield coverage (modellableYield), and the Morpho sUSDat/AUSD market (0x582fdc41…5065, about $5.7M borrowed) stays a blocked_adapter decision, never a proposal, until sUSDat has a quoted or smoothed rate.
  • sUSDat now has a rate, so the pricing-category check reads it: it may propose sUSDat as redemption-priced (its DEX market is thin). A proposal is Fred's call, never applied by this release.

In release v0.87.0 this entry ships with Saturn's, StakeWise's, 142's, apxUSD and apyUSD's book and the coverage floor's last two steps, and they run as one order: the combined pass (this entry's steps 1 and 2 are its step 1, before the merge). Its order and numbers win where they differ from the steps below.

Prod, in order. Steps 1 and 5 write prod and need the owner's go.

  1. GATED: migration 141, BY HAND, BEFORE the merge, from the staging checkout at the release PR's head:

    bash
    git -C /opt/onchain-credit-staging rev-parse HEAD                      # = the release PR's head commit
    git -C /opt/onchain-credit-staging status --porcelain -- scripts/sql   # prints nothing
    f=141-susdat-usd-book
    sudo -u postgres env "PGOPTIONS=-clock_timeout=10s -cstatement_timeout=300s" \
      psql -v ON_ERROR_STOP=1 -X -q -1 -d creddit -f /opt/onchain-credit-staging/scripts/sql/$f.sql \
    && sudo -u postgres psql -q -d creddit -c "INSERT INTO onchain_credit.schema_migrations(filename) \
         VALUES ('$f.sql') ON CONFLICT DO NOTHING"
    sudo -u postgres psql -d creddit -At -c "SELECT symbol, book, class, valuation, feed, underlying_address, rate_source, rate_kind, rate_getter FROM onchain_credit.portfolio_tokens WHERE chain_id = 1 AND address = '0xd166337499e176bbc38a1fbd113ab144e5bd2df7'"
    # sUSDat|USD|variable_rate|market|dune_tape|0x23238f20b894f29041f48d88ee91131c395aaa71|0xd166337499e176bbc38a1fbd113ab144e5bd2df7|getter|{"kind": "erc4626", "divisorPow10": 6}

    One that aborts on lock_timeout is run again when quiet. The standing runner then finds 141 recorded and skips it.

  2. Read-only, after step 1 and before the merge: the plan, from the staging checkout against prod's database (it judges readings against the database's book, so it sees sUSDat only once 141 is applied):

    bash
    cd /opt/onchain-credit-staging
    ( set -a && . /opt/onchain-credit/.env.local && set +a && \
      npx tsx scripts/ops/restate-covered-readings.ts --plan --db-url "$DATABASE_URL" )

    Every would restate … sUSDat (0xd166…2df7) line is a wallet whose history this release re-prices: record the wallets. A held back … no redemption rate at its block line is a reading at an STRC outage block: step 5's series clears it at a later pass. Any other asset's line is another widening: read it before merging.

  3. The merge and the deploy, straight after step 2. The deploy restarts the app, the ingester and the ledger worker; the app's restart is the one that loads 141's row (the other two re-read the registry every five minutes anyway). Check, read-only, that the app restarted after step 1: pm2 ls shows onchain-credit online with an uptime shorter than the time since step 1. If it did not, it still holds the old row: pm2 restart onchain-credit --update-env before going on.

  4. The first six-hourly refresh-assets tick after the deploy (or a hand run once the deploy has finished: scripts/run-cron.sh refresh-assets.ts). Check, read-only: SELECT snapshot_ts, share_rate, supply_apy, apy_30d, block_at_snapshot FROM onchain_credit.token_yield_apy WHERE token_address = '0xd166337499e176bbc38a1fbd113ab144e5bd2df7' ORDER BY snapshot_ts DESC LIMIT 3 returns a fresh row near 1.04 (1.041001 at block 26,154,529) with supply_apy and apy_30d NULL, and no [token-yields/fail] … sUSDat line.

  5. GATED: the trailing window of sUSDat's rate series (the runner). Read-only plan first, then with the go:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    T=0xd166337499e176bbc38a1fbd113ab144e5bd2df7
    npx tsx scripts/ops/backfill-token-rate-series.ts --db-url "$DATABASE_URL" --token $T --plan
    npx tsx scripts/ops/backfill-token-rate-series.ts --db-url "$DATABASE_URL" --token $T --execute | tee /tmp/susdat-rate-series.log
    npx tsx scripts/ops/backfill-token-rate-series.ts --db-url "$DATABASE_URL" --token $T --execute | tail -1   # nothing to write

    Expect a 45-day window of 181 boundaries and 0 failed (the measured outage falls between the 06:00 and 12:00 boundaries). A boundary that fails on every run sits inside another STRC outage: record it and stop re-running; the reading falls back to the row before it. Every written row has supply_apy and apy_30d NULL; backfill-apy-30d.ts skips sUSDat, so a later run of it leaves them so.

  6. Check, read-only, once the worker's pass and its re-derivations are done (its [restate] done: line, no rederive queued or running): no sUSDat reading left EXCLUDED except ones the plan held back and a later pass has not yet cleared:

    sql
    SELECT book, count(*) FROM onchain_credit.portfolio_position_snapshots
     WHERE chain_id = 1 AND accounting_asset = '0xd166337499e176bbc38a1fbd113ab144e5bd2df7' GROUP BY 1;

    and on the next reconciler run, book-overlays=0 for step 2's wallets. On /portfolio, one of them reads sUSDat in the USD view under Variable rate assets with a dash for 24h APY, and a USDC or AUSD loan against sUSDat under Carry trades. The next carry-discovery run proposes no sUSDat carry (the sUSDat/AUSD market reads blocked_adapter).

  7. Record executed: with the date, step 1's row, step 2's lines, step 5's summary line and step 6's counts.

Staging. Migration 141 auto-applies there with the staging deploy, which restarts the staging app; no staging seed account holds sUSDat, so nothing restates and no golden moves. A staging series backfill is undone by the nightly reseed.

Rollback. A code rollback does not roll back the database. The previous release, restarted, reads sUSDat's row from the database's registry and values it in the USD book through the rate getter it already has, so its readings stay restated. The previous refresher has no sUSDat entry, so it stops writing the series; the rows already written carry no APY, so nothing the previous release shows reads a figure from them. Undoing the book itself is a forward change: a migration back to book NULL, after which the restatement reports sUSDat as narrowed (NOT restated) at every pass, and that history stays as written.

Condition 1 counts the rows a band measured (migration 142): prod steps, in order ​

  • belongs to: migration 142 (additive: the address list on a recorded band), pushed directly to staging on 2026-10-12 with Fred's go; it unblocks the coverage floor's steps 3 and 4
  • executed: 2026-10-12
  • run record: (2026-10-12.) The code: commit 1494b3a2 pushed directly to staging (staging deploy run 38221437650 green at 08:06Z: APPLY: 142-ledger-band-measured-addresses.sql, 1 applied; smoke green). The nine stale coverage rows (Fred's go of 2026-10-12 to remove them, after a read-only pre-check), pre-check 07:44Z to 07:57Z: exactly nine event_coverage rows name the nine addresses, all erc4626, live over [22527558,25840566], last written 2026-08-26 16:58:14Z; no other stream holds a row for them. The code that reads coverage asks only about addresses something requires: the ingester's catch-up takes the declared addresses not yet live; the served completeness check, the tick's coverage tripwire, the reconciler's certified set and the acceptance gate's condition 4 look up the keys a wallet's positions or the declared set name; and the nine tokens are retired from the registry, so none of them reads the rows. No reading row has ever named one of the nine tokens. On chain at the head, 135 balance reads (the 15 enrolled or recently read wallets × the nine tokens): one non-zero, the prod test wallet 0xdd647ce1…c737 holding 0.000347563 USD1 (0x8d0d000e…0b0d), with no USD1 transfer in its stored history (from block 25,928,920). That broke the pre-check's "no enrolled wallet holds those tokens", so the delete was held; Fred confirmed the removal the same morning (that test wallet is to be deleted, so its dust does not matter). Backup taken (read-only): /var/tmp/v0860/retired-coverage-backup.sql (nine INSERT … ON CONFLICT DO NOTHING lines, the restore) and retired-coverage-backup.csv (nine rows); the delete ran at 08:22:22Z (/var/tmp/v0860/retired-coverage-delete.sql, one transaction that aborts unless exactly nine rows go; NOTICE: deleted 9 rows, COMMIT; log retired-coverage-delete.log): erc4626 now holds 639 live of 639 keys, and no coverage row names any of the nine addresses. No stored event was touched. Reported and kept: two wallet-token rows on stUSDS from 2026-09-19 for wallets not enrolled today (block 26,008,790 log 121, a mint to 0x90fff1da…4dfb; block 26,008,796 log 1467, 0x90fff1da…4dfb to 0x4a6c312e…0ae0). Baseline read-only --verify --stream erc4626 on v0.86.0 (07:47:03Z to 07:48:09Z, verify-erc4626-before.log): condition 1 MISS (1,455,064 over [22527558,25840566] vs [1254735,1254735], the old band), condition 2 pass (2,591 receipts, no gap), condition 3 MISS on [25177558,25227557] (the stale-record effect, the coverage floor's step 4), condition 4 MISS on one declared vault with no coverage row at all, 0x3bd9adae…9478 (not declared on 2026-10-11, and no catch-up line for it in the ingester's log): none of the four reads the nine rows, so removing them cannot move any of them. After the delete (08:22:29Z to 08:23:17Z, verify-erc4626-after.log): identical, line for line, apart from the head block and condition 3's randomly drawn record ([24177558,24227557], the same stale-record MISS); same run tag ccd3c0f22ed7.
  • run record, the new vault with no coverage: (2026-10-12, read-only, then one documented restart.) 0x3bd9adae…9478 is RockawayX Tori Ecosystem (roxTORI, a USDC Morpho vault), listed in the money-market fund registry at 2026-10-12 03:55:15Z. The ingester had been running since 2026-10-11 21:29:25Z (the v0.86.0 deploy). Its five-minute registry refresh calls loadRegistries, but the fund registry reaches that through initRegistries, which installs the token and fund rows once per process and never again (resetRegistryInit has no production caller); the MetaMorpho factory rows, by contrast, are re-read on every refresh. So a fund listed after the ingester starts is missing from its transfers and erc4626 surfaces until the next restart, which docs/deployment.md (#ingester-restart, and the worker's "restart it by hand after editing a registry row it should see") gives as the remedy. pm2 restart creddit-event-ingester --update-env at 08:24:22Z: the vault's catch-up ran from the floor on both streams ([ingester/transfers] caught up 0x3bd9adae… [24136053,26175159] wrote 34 log(s) at 08:34:28Z, [ingester/erc4626] caught up … wrote 13 log(s) at 08:34:31Z, after six progress windows), 0 cycle error, no other address pending; both coverage rows live from 24136053; erc4626 640 live of 640. Read-only --verify --stream erc4626 again (verify-erc4626-after-restart.log): condition 4 now pass · 2 anchor(s) present · 640/640 declared address(es) live from the floor; conditions 1 (1,455,150 against the old band) and 3 (stale record) miss as before. For the coverage floor's step 3: the declared set is now 640, the stored rows over [24136053,25840566] are 792,696 (the new vault adds 86), so the measurement should read 784,903 across 640 (792,696 less stUSDS's 7,793). The underlying defect is open (not fixed here): a fund listed between deploys does not reach the ingester until a restart, so its history is not caught up meanwhile (the ledger worker installs the registries the same once-per-process way, per docs/deployment.md, so it was not restarted here and may need the same). The likely fix is for the ingester's five-minute refresh (and the worker's registry reload) to reset the registry install before reloading.
  • run record: (v0.87.0, release PR #1126, merge 1284e4c7 at 17:10:33Z on 2026-10-12, deploy run 38282474222 green 17:10:41Z to 17:11:55Z: app, ingester and worker restarted 17:11:53Z to 17:11:55Z, health 200, box on 0.87.0; 141 by hand at 17:10:13Z before the merge; one migrate.sh at 17:12:34Z to 17:12:41Z: 5 applied (140, 142, 143, 144 and #1124's 145), 144 total on disk; run as the combined pass.) Step 1: the run's APPLY: 142-ledger-band-measured-addresses.sql; measured_addresses|ARRAY|YES. Step 2: the coverage floor's steps 3 and 4 (its v0.87.0 record): recorded erc4626=784903 over [24136053,25840566] with address list: erc4626 640 address(es), and erc4626's condition 1 exact with 7793 stored row(s) on addresses in neither, not counted; escrow's band from v0.87.0's pass carries its 15-address list.

What it changes for a user, in one line: nothing visible. It lets the historical acceptance check pass on a complete event history after the token list has shrunk.

Why. Condition 1 of the historical acceptance gate compares the stored rows over a band's range with the band's independent count. Before 142 it counted every stored row of the stream, and the band recorded only how many addresses it measured (138), which holds while a declared set only grows. It also shrinks: migration 105 (2026-09-17) retired eleven registry rows, and a retired address leaves every set built from the registry while its stored rows stay. Nine of them dropped out of erc4626's declared set (stUSDS 0x99cd4ec3…eeb9, USR 0x66a1e37c…e110, eUSD 0xa0d69e28…482f, USD1 0x8d0d000e…0b0d, USD0 0x73a15fed…acf5, GUSD 0x056fd409…d5cd, TUSD 0x00000000…b376, USDD 0x0c10bf8f…b5c6, FDUSD 0xc5f0f7b6…6409). The v0.86.0 re-measure (2026-10-11, dry run) measured 784,817 rows across the 639 declared addresses, while the stored corpus over [24136053,25840566] holds 792,610: the difference is exactly stUSDS's 7,793 kept rows (the other eight never emit an ERC-4626 event). Recorded as it stood, the band would fail.

What it does. The recorder now stores WHICH addresses it measured (measured_addresses), and the gate counts stored rows only on those plus the addresses declared since: an address retired before the measurement is neither counted nor a failure (its rows are kept, never deleted); a measured address retired since still counts; the 7,000-row headroom per vault counts the vaults listed since by address, not by the difference of two counts. Bands recorded before 142 (every band on prod today) count every stored row exactly as before. fluid-operate (chain-wide) and wallet-token (filtered on wallets) record no list, because their stored rows are not keyed on what they declare. No served number moves; the migration changes the fixture's schema, so the goldens' manifest was regenerated with no figure moving.

In release v0.87.0 this entry ships with Saturn's, StakeWise's, sUSDat's book, apxUSD and apyUSD's book and the coverage floor's last two steps, and they run as one order: the combined pass (step 1 below is its step 3, which applies 140, 143 and 144 too; step 2 is its step 15). Its order and numbers win where they differ from the steps below.

Prod, in order. Step 1 writes prod and needs Fred's go; step 2 is the coverage floor's steps 3 and 4.

  1. GATED: apply migration 142, after the release carrying it is deployed:

    bash
    cd /opt/onchain-credit && scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)"

    migrate.sh applies every pending file (any other migration that release carries comes with it; follow its own entry). Expect 142-ledger-band-measured-addresses.sql applied. Read-only check: SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema = 'onchain_credit' AND table_name = 'ledger_backfill_acceptance_bands' AND column_name = 'measured_addresses' returns measured_addresses|ARRAY|YES. Until it lands the gate reads every band without the list (every stored row counts) and the recorder's insert fails, so apply it first.

  2. Then the coverage floor's step 3 (GATED: erc4626's re-measure) and step 4 (read-only: the gate over every stream), with the figures written there: measured 784,903 across 640 addresses on 2026-10-12 (784,817 across 639 on 2026-10-11, before RockawayX Tori caught up; more if vaults were listed since), an address list of the same count, and in step 4 erc4626's condition 1 exact with 7793 stored row(s) on addresses in neither, not counted. Step 4 runs only after the escrow completion of the same release (v0.87.0's combined pass, step 10): before it escrow's condition 4 misses on the two new queues' keys.

  3. Record executed: here with step 1's line, and the coverage floor's record with its steps.

Separately, Fred's decision: the nine stale coverage rows. event_coverage held nine erc4626 rows reading live from 22,527,558 to 25,840,566 for those retired addresses, a "history complete" claim nothing maintains since the retirement. Nothing current reads them (the ingester and every certificate check ask only about declared addresses, and no reading has ever valued one of the nine tokens), but if a token were listed again the stale row would let its catch-up skip the gap since 2026-09-17. Removing them is approved in principle; the 2026-10-12 pre-check found the prod test wallet 0xdd647ce1…c737 holding 0.000347 USD1 (never read or valued: no reading row for any of the nine tokens, no USD1 transfer in its stored history), so the delete was held for a word from Fred. The rows are backed up at /var/tmp/v0860/retired-coverage-backup.sql (restore script) and .csv, and the one-transaction delete that aborts unless exactly nine rows go is staged at /var/tmp/v0860/retired-coverage-delete.sql. Fred confirmed the removal and it ran on 2026-10-12 at 08:22Z (exactly nine rows); with RockawayX Tori caught up the same day, step 2's key counts read 640 (read on prod, 2026-10-12).

Staging. 142 auto-applies there; nothing else applies (no ingester, and the nightly reseed wipes any band).

Rollback. The column is inert under the previous code, which reads only declared_addresses. A band recorded with the list then counts every stored row again, so erc4626's verify reads red (792,696 against a ceiling of 784,903, on 2026-10-12's figures) until a forward release; nothing served reads either.

apxUSD and apyUSD join the USD book (migration 143, #1087): prod steps, in order ​

  • belongs to: apxUSD's and apyUSD's registry rows (branch oc-1087-apyx-book), migration 143. Ships in the same release as the Apyx unlock receipt (139, its entry) or a later one, never before it: see "Order" below
  • executed: 2026-10-12
  • run record: (v0.87.0, release PR #1126, merge 1284e4c7 at 17:10:33Z on 2026-10-12, deploy run 38282474222 green 17:10:41Z to 17:11:55Z: app, ingester and worker restarted 17:11:53Z to 17:11:55Z, health 200, box on 0.87.0; 141 by hand at 17:10:13Z before the merge; one migrate.sh at 17:12:34Z to 17:12:41Z: 5 applied (140, 142, 143, 144 and #1124's 145), 144 total on disk; run as the combined pass.) Step 2 (by the migrate.sh run): the rows read apxUSD|USD|par|market||0x98a878b1cd98131b271883b390f68d2c90674665|getter|{"kind": "chainlink_feed", "target": "0x651b101f72f82630cf59c68e6ee4305afbd3b1f5", "parBeforeTs": 1776956459, "divisorPow10": 18, "heartbeatSec": 86400, "parBeforeBlock": 24943407} and apyUSD|USD|variable_rate|market|0x98a878b1cd98131b271883b390f68d2c90674665|0x38eeb52f0771140d10c4e9a9a72349a329fe8a6a|getter|{"kind": "erc4626", "divisorPow10": 18}. Step 3: pm2 restart onchain-credit --update-env at 17:12:54Z (13 s after the run). Step 3b: D 173, plan 693 boundaries; apxUSD: 693 row(s) written in 15 statement(s), 0 kept, 0 failed; … share_rate 0.78205 .. 1; the 5 rows before block 24,943,407 read 1, the 2026-06-26 18:00 boundary 0.793825, every row with both APYs NULL; a second plan 0 to write. Reloads: the worker [registry] reloaded: token registry (104 rows) and … a coverage restatement pass starts now at 17:16:56Z, the ingester's reload at 17:17:56Z; the pass: 0x272c39c8…2e2c apyUSD 154 and apxUSD 100 readings, 0x5bc81274…04c2 apyUSD 38 and apxUSD 27, 0xaae6ae86…d050 apyUSD 47, then [restate] done: 2 asset(s) widened, 3 wallet(s) visited, 366 reading(s) restated, 0 held back, 7 carried copies restated, 3 rederive job(s) queued at 17:18:02Z (#2266, #2267, #2270). Step 4 (plan, run after that pass): nothing to restate: every stored reading agrees with the registry's book; no held back … beside its own line anywhere. With sUSDat's pass the combined total is 480 readings of 4 wallets and 9 carried copies, as expected. Step 5 (the 18:00Z tick): apyUSD|2026-10-12 18:00|1.4412097268973547|0.12647764333945477|0.13853818734609802|26178045, apxUSD|…|1|||26178045, [redemption-feeds] 1 published redemption value feed(s) checked, 0 finding(s), no [token-yields/fail] line for either. The tick's standing alert (quiet market prices: apyUSD quiet since 2026-10-08 06:00Z, rUSD since 10-06) predates the release (it read the same at 12:00Z). Step 6: plan 181 boundaries; apyUSD: 181 row(s) written in 4 statement(s), 0 kept, 0 failed … share_rate 1.4186948958090047 .. 1.4410921686503002; second --execute: nothing to write. Step 7 (no rederive queued or running): apyUSD USD|239, apxUSD USD|127, no EXCLUDED; without_own_rate 0 and apyusd_without_apxusd 0 on both; the reconciler book-overlays=0, exit 0, no refused figure and no payout-rate line for 0x272c39c8…2e2c, 0x5bc81274…04c2 and 0xaae6ae86…d050. The two refused figures v0.86.0's record left open on 0x272c39c8…2e2c no longer print; its audit still reads partial … 86 unread … escrow:apyx-apyusd-unlock-receipt:993, as it did after the v0.86.0 re-derive (readings older than the class, no adjustment booked). /portfolio and carry discovery were not looked at (no browser check was approved).

What it changes for a user, in one line: a wallet holding apxUSD sees it in the USD view under Idle assets (no 24h APY), and one holding apyUSD sees it under Variable rate assets with a 24h APY, where until now both showed in the All view only. Net asset value and MTM PnL follow each one's market price; Accrual only PnL follows the Redemption Value Apyx publishes for apxUSD (and, for apyUSD, its vault rate on top), so a fall in the preferred stock behind apxUSD shows there too, and the gap is Dislocation P&L. An apyUSD redemption In settlement moves to the USD view with it. A USDC or apxUSD loan against either moves from Cross-currency borrowing to Carry trades, and a Pendle PT paying out apxUSD (PT-apyUSD, PT-apxUSD) moves into the USD view.

Why. Fred's rulings of 2026-10-12, correcting the premise 141's entry stated: Apyx PUBLISHES apxUSD's redemption value on chain (Chainlink "APXUSD / USD Exchange Rate", proxy 0x651b101f72f82630cf59c68e6ee4305afbd3b1f5, answering since block 24,943,407 on 2026-04-23), so there is an issuer figure for the accrual line. apxUSD is treated like any dollar (it clears every market bar), and apyUSD's rate is real accrual.

What it does, and what it leaves.

  • Code plus one additive migration (143: two UPDATEs; apxUSD: book, rate_source, rate_kind, rate_getter (the feed, with the dated parBeforeBlock 24,943,407 and its timestamp parBeforeTs, and a 24h heartbeatSec); apyUSD: book, underlying_address (apxUSD), rate_source, rate_kind, rate_getter (erc4626, divisor 18)). No class, term, kind, feed or valuation moves: apxUSD stays an idle (par) row and both stay market-valued at their own tape.
  • Before the feed's first answer apxUSD's redemption value is one dollar (the dated fallback); from that block a feed that does not answer WITHHOLDS the figure, and the writers never fall back to the six-hourly series for it. The new six-hourly step redemption-feeds (in refresh-assets.ts) pages in words when the feed stops answering or updating.
  • Migration 143 is applied by hand AFTER the deploy, and the app is restarted straight after it (the reverse of 141's order, for the reason the file's header gives: the previous release cannot read a par row with a redemption getter and would value apxUSD at one dollar against the new row, and its ingester and worker would load that row within five minutes on their own; the new release against the old row behaves exactly as today). The app, the ingester and the ledger worker all re-read the registry every five minutes (no restart needed), and the worker's reload that sees the change starts the restatement pass. The app is restarted anyway: it reads book per request but its rate getters from its loaded copy, so until its reload it would value apxUSD's accrual line at one dollar.
  • The worker restates existing wallets' apxUSD and apyUSD history by itself (the procedure): readings stored EXCLUDED (bare holdings, the In settlement receipt, PT legs paying out apxUSD) are restated into the USD book from the pass its first reload after step 2 starts (within five minutes), a few wallets per turn, and each wallet's rederive is queued. Never run restate-covered-readings.ts --execute by hand in this release.
  • apyUSD's value reads two rates, and the restatement states both (the release v0.87.0 review's B2, fixed on staging before the release merged): apyUSD's redemption value is its vault rate times apxUSD's published value, so a restated apyUSD reading carries its vault rate in rate_raw and both rates in rate_facts, each read at the reading's block exactly as a writer reads them, which is the row a writer covering apyUSD all along would have stored. Without that fix every apyUSD reading was held back (its value in USD reads a rate beside its own (0x98a8…4665)), and a holder such as 0x272c39c8…2e2c would have kept a blank MTM PnL and Accrual only PnL in the USD view over its apyUSD stretches. A reading at a block where apxUSD's feed does not answer is still held (no redemption rate at its block, never stated at 0 or 1) and asked about again at every pass.
  • The same fix covers history earlier releases held for the same reason: a PT leg whose payout asset is composed (PT-fxSAVE over the pool share fxSP; see its entry, step 5). The pass restates any such reading still stored, the payout asset's rate in its rate_facts, and re-derives its wallet; none are on prod as of 2026-10-12.
  • The loan reclassification is read time: it shows from the app's restart, before any restatement.
  • The yields refresher observes both from this release: apyUSD with its APY (the 24h APY cell, its run rate), apxUSD as a rate-only row holding the published value (no APY). The PT accrual line over a PT paying out apxUSD converts every flow and level at that stored value, so apxUSD's series is filled back to the feed's start in step 3b, RIGHT AFTER the restart and under step 2's go. Until it is, every PT-apyUSD and PT-apxUSD leg withholds at each date the series does not reach, and under the financed- and wallet-level rule (M9) that blanks the holder's whole USD Accrual only PnL there and counts against the reconciler's budget. If step 3b is delayed, expect the ledger self-check to page those wallets with "payout asset's rate missing" lines for PT-apyUSD / PT-apxUSD; they clear at the next run after the fill. (PT-sUSDat needs no fill: both its markets settle in USDat, a par dollar; see the PR.)
  • Carry proposals will appear (Fred, 2026-10-12: allowed). apyUSD gains a yield row, so the Morpho apyUSD/USDC and apyUSD/apxUSD markets stop reading blocked_adapter and are PROPOSED on the next carry-discovery run, for Fred's consent; nothing is listed without it. apxUSD, an idle dollar, is held out of discovery as collateral (it has no yield to model), exactly as before it had a row.
  • The pricing check reads apyUSD now (it is booked and yield-bearing). Its deepest pool is Curve apyUSD/apxUSD (about $16.8M on 2026-10-12), so it is likely to stay market-priced; any proposal is Fred's call, never applied by this release. apxUSD, an idle dollar, is never tested.
  • apxUSD's live price is judged against its published value, not a dollar (3% band). In June and July 2026 the market sat a median 3.7% under that value: a lone vendor quote that far off is not served and the hourly bar stands; two vendors agreeing within 1% are served.

If 143 is applied by a migrate.sh run (another entry's step in the same release: 142's, which is step 3 of v0.87.0's combined pass), that run IS step 2. Do step 3 (restart the app) straight after that run, and step 3b straight after it; step 2's own commands are then only its read-only row check, and the combined pass's expected applied count includes 143. Without the restart the app values apxUSD's accrual line at one dollar for up to five minutes (its reload): harmless while the feed reads exactly 1.0, as it has since 2026-09-17, and wrong the day it does not.

Order. 139 (the Apyx unlock receipt model) must be on prod first or in the same release: booked USD without it, an open apyUSD redemption would take the unmodelled-exit shape inside the USD view (missing from Net asset value while it waits, its payout landing as money added). 143 is independent of 140 and 141 (Saturn's rows).

In release v0.87.0 this entry ships with Saturn's, StakeWise's, sUSDat's book, 142's and the coverage floor's last two steps, and they run as one order: the combined pass, right after this entry. Its order and numbers win where they differ from the steps below; step 7 is the one it refers to as written here.

Prod, in order. Steps 2, 3 and 3b go together under one go (3b is the apxUSD fill, which cannot run before 143 because the runner needs the booked row); step 6 (apyUSD's 45 days) has its own.

  1. The merge and the deploy. Nothing about apxUSD or apyUSD changes yet: the database's rows still book both NULL, which the new code reads exactly as the old one did.

  2. GATED: migration 143, BY HAND, straight after the deploy is green, from the prod checkout:

    bash
    git -C /opt/onchain-credit rev-parse HEAD                      # = the release's merge commit
    git -C /opt/onchain-credit status --porcelain -- scripts/sql   # prints nothing
    f=143-apyx-usd-book
    sudo -u postgres env "PGOPTIONS=-clock_timeout=10s -cstatement_timeout=300s" \
      psql -v ON_ERROR_STOP=1 -X -q -1 -d creddit -f /opt/onchain-credit/scripts/sql/$f.sql \
    && sudo -u postgres psql -q -d creddit -c "INSERT INTO onchain_credit.schema_migrations(filename) \
         VALUES ('$f.sql') ON CONFLICT DO NOTHING"
    sudo -u postgres psql -d creddit -At -c "SELECT symbol, book, class, valuation, underlying_address, rate_source, rate_kind, rate_getter FROM onchain_credit.portfolio_tokens WHERE chain_id = 1 AND address IN ('0x98a878b1cd98131b271883b390f68d2c90674665', '0x38eeb52f0771140d10c4e9a9a72349a329fe8a6a') ORDER BY symbol"
    # apxUSD|USD|par|market||0x98a878b1cd98131b271883b390f68d2c90674665|getter|{"kind": "chainlink_feed", "target": "0x651b101f72f82630cf59c68e6ee4305afbd3b1f5", "parBeforeTs": 1776956459, "divisorPow10": 18, "heartbeatSec": 86400, "parBeforeBlock": 24943407}
    # apyUSD|USD|variable_rate|market|0x98a878b1cd98131b271883b390f68d2c90674665|0x38eeb52f0771140d10c4e9a9a72349a329fe8a6a|getter|{"kind": "erc4626", "divisorPow10": 18}

    One that aborts on lock_timeout is run again when quiet. The standing runner then finds 143 recorded and skips it.

  3. GATED: restart the app AT ONCE, so it loads the new rows now rather than at its next five-minute reload (until then it would book apxUSD USD per request with no getter for it, valuing its accrual line at one dollar):

    bash
    pm2 restart onchain-credit --update-env
    pm2 ls   # onchain-credit online, uptime shorter than the time since step 2

    The ingester and the ledger worker need no restart: within five minutes each logs a [registry] reloaded … line, and the worker [worker] the token or fund registry changed on reload; a coverage restatement pass starts now. Until then they hold the old rows: the worker holds the two assets back ([restate] held back … reload), the ingester writes new readings EXCLUDED (restated afterwards), and nothing is written wrong. 3b. GATED with step 2: apxUSD's series back to the feed's start, straight after step 3 (the runner):

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    T=0x98a878b1cd98131b271883b390f68d2c90674665
    D=$(( ( $(date -u +%s) - $(date -u -d 2026-04-22 +%s) ) / 86400 ))
    npx tsx scripts/ops/backfill-token-rate-series.ts --db-url "$DATABASE_URL" --token $T --days $D --plan
    npx tsx scripts/ops/backfill-token-rate-series.ts --db-url "$DATABASE_URL" --token $T --days $D --execute | tee /tmp/apxusd-rate-series.log

    Expect 0 failed. Rows before block 24,943,407 read one (the dated fallback) and every later one the feed's value at its boundary (0.793825 at the 2026-06-26 18:00 boundary); all of them carry supply_apy and apy_30d NULL. A second --execute writes nothing.

  4. Read-only: the plan, against prod's database (it judges readings against the database's book):

    bash
    cd /opt/onchain-credit
    ( set -a && . ./.env.local && set +a && \
      npx tsx scripts/ops/restate-covered-readings.ts --plan --db-url "$DATABASE_URL" )

    Every would restate … apxUSD (0x98a8…4665) or … apyUSD (0x38ee…8a6a) line is a wallet whose history this release re-prices: record the wallets (the worker's reload pass may already have restated a first few, which then no longer appear). 0x272c39c8…2e2c is expected among the apyUSD lines. A held back … apyUSD … reads a rate beside its own line must NOT appear: it means the running worker or checkout predates the B2 fix, so stop and check the deploy. A held back, left EXCLUDED: <n> no redemption rate at its block on apxUSD or apyUSD names readings from block 24,943,407 on where the feed did not answer (an archive outage); every pass asks again. Any other asset's line is another widening: read it before going on.

  5. The first six-hourly refresh-assets tick after step 2 (or a hand run: scripts/run-cron.sh refresh-assets.ts). Check, read-only:

    sql
    SELECT token_symbol, snapshot_ts, share_rate, supply_apy, apy_30d, block_at_snapshot
      FROM onchain_credit.token_yield_apy
     WHERE token_address IN ('0x98a878b1cd98131b271883b390f68d2c90674665', '0x38eeb52f0771140d10c4e9a9a72349a329fe8a6a')
     ORDER BY snapshot_ts DESC LIMIT 4;

    apyUSD near 1.44 (1.441013 at block 26,175,038) with its APY once a day of rows exists; apxUSD at the feed's value (1.0 since 2026-09-17) with supply_apy and apy_30d NULL. The log has one [redemption-feeds] 1 published redemption value feed(s) checked, 0 finding(s) line and no [token-yields/fail] … apyUSD or … apxUSD line.

  6. GATED: apyUSD's series, the trailing 45 days (the runner), as any wrapper joining the refresher. Read-only plan first, then with the go:

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    T=0x38eeb52f0771140d10c4e9a9a72349a329fe8a6a
    npx tsx scripts/ops/backfill-token-rate-series.ts --db-url "$DATABASE_URL" --token $T --plan
    npx tsx scripts/ops/backfill-token-rate-series.ts --db-url "$DATABASE_URL" --token $T --execute | tee /tmp/apyusd-rate-series.log

    Expect 0 failed. A second --execute writes nothing.

  7. Check, read-only, once the worker's pass and its re-derivations are done (its [restate] done: line, no rederive queued or running): no apxUSD or apyUSD reading left EXCLUDED:

    sql
    SELECT accounting_asset, book, count(*) FROM onchain_credit.portfolio_position_snapshots
     WHERE chain_id = 1 AND accounting_asset IN ('0x98a878b1cd98131b271883b390f68d2c90674665', '0x38eeb52f0771140d10c4e9a9a72349a329fe8a6a')
     GROUP BY 1, 2;

    and no restated reading without the redemption rate its value reads (a transient archive failure during the pass leaves one; the next pass retries it, because a failed published-value read is never cached):

    sql
    SELECT accounting_asset, count(*) AS readings,
           count(*) FILTER (WHERE rate_raw IS NULL) AS without_own_rate,
           count(*) FILTER (WHERE accounting_asset = '0x38eeb52f0771140d10c4e9a9a72349a329fe8a6a'
                              AND NOT coalesce(rate_facts ? '0x98a878b1cd98131b271883b390f68d2c90674665', false)) AS apyusd_without_apxusd
      FROM onchain_credit.portfolio_position_snapshots
     WHERE chain_id = 1 AND book = 'USD'
       AND accounting_asset IN ('0x98a878b1cd98131b271883b390f68d2c90674665', '0x38eeb52f0771140d10c4e9a9a72349a329fe8a6a')
     GROUP BY 1;

    Both without_… columns read 0 once a pass has run after a failed read (a restated apyUSD reading carries apxUSD's published value in its rate_facts: the B2 fix, above). And on the next reconciler run, book-overlays=0 for step 4's wallets (0x272c39c8…2e2c included) and no "payout asset's rate missing" line for a PT-apyUSD / PT-apxUSD leg. On /portfolio, one of them reads apxUSD in the USD view under Idle assets with no 24h APY, apyUSD under Variable rate assets with one, and a USDC loan against either under Carry trades. The next carry-discovery run PROPOSES the Morpho apyUSD/USDC and apyUSD/apxUSD markets (Fred decides). Once one is listed, its /carries peg chart and basis quote measure apxUSD (and apyUSD through it) against Apyx's published Redemption Value, the same stored series step 3b fills, not against a dollar.

  8. Record executed: with the date, step 2's rows, step 3b's and step 6's summary lines, step 4's lines and step 7's counts.

Staging. Migration 143 auto-applies there with the staging deploy, which runs migrate.sh before its restart, so staging is consistent at once. A staging series backfill is undone by the nightly reseed.

Rollback. A code rollback does not roll back the database, and the previous release, restarted against these rows, would value apxUSD's redemption at one dollar (its par class). So a rollback is preceded by a forward change that books both rows NULL again (UPDATE … SET book = NULL on the two addresses), after which the restatement reports them narrowed (NOT restated) at every pass and their history stays as written. The series rows left behind carry apyUSD's APY and apxUSD's value; the previous release reads apyUSD's for its 24h APY only while apyUSD is booked, which it then is not.

Release v0.87.0: the six entries as one prod order ​

v0.87.0 carries Saturn's queue (140), sUSDat's USD book (141), condition 1's address list (142), this entry (143) and StakeWise's queue (144), plus the two steps the coverage floor left over from v0.86.0 (its steps 3 and 4). They share one migrate.sh run, one escrow sweep, one band, one completion run and one re-derive, so they run as this one order. Each entry's own step holds the query and what its lines mean; the numbers here are the ones that hold when all of them ship together, and they win where an entry differs. GATED steps write prod and need Fred's go. Figures marked (prod, 2026-10-12) or (chain, 2026-10-12) were re-read read-only for this order, and (code) ones counted from the release's registry; the rest are the release review's (PR #1126) or the entry's own.

143 ships with the restatement writing apyUSD's second rate (apxUSD's published value beside apyUSD's own: option (a) of the release review's B2, landed on staging by PR #1129); this entry's step 7 checks for it. (The review's fallback, option (c), holding 143 and applying 140, 142 and 144 by hand, is no longer needed and is kept here only as a record.)

  1. Before the merge, read-only:

    • SELECT filename FROM onchain_credit.schema_migrations WHERE filename >= '137' ORDER BY 1: 137, 138 and 139, none of 140 to 144 (prod, 2026-10-12).
    • The escrow baseline B (step 7's query): 171,643, the band v0.86.0 recorded (prod, 2026-10-12). Escrow coverage: 9 keys live, seven at 22,527,558 and the Stader manager and Apyx receipt at 24,136,053 (prod, 2026-10-12).
    • erc4626: 640 of 640 keys live, and 784,903 stored rows on them over [24136053,25840566], out of 792,696 in all; stUSDS's 7,793 have no key since the nine retired rows were removed (prod, 2026-10-12). More if vaults were listed since.
    • Saturn's step 0 and StakeWise's step 0. Record the lines; a non-zero tickets_at_floor is named in the run record, not a stop.
    • The staging checkout is at the release PR's final head and git status --porcelain -- scripts/sql prints nothing.
  2. GATED: 141 by hand, then its read-only plan (sUSDat's steps 1 and 2). Record the would restate … sUSDat wallets; a held back … no redemption rate at its block line is an STRC outage reading. Merge straight after.

  3. The merge (a merge commit), the prod deploy, health 200. pm2 ls: the app, the ingester and the ledger worker all restarted after step 1.

  4. GATED: one migrate.sh run (142's step 1). Expect 4 applied: 140, 142, 143 and 144 (141 is already recorded). Read-only row checks: sUSDat|queued|{ethereum}|saturn-susdat-withdrawal-queue (Saturn step 1), osETH|queued|{ethereum}|stakewise-oseth-exit-queue (StakeWise step 1), measured_addresses|ARRAY|YES (142 step 1) and the apxUSD and apyUSD rows of this entry's step 2. This run IS this entry's step 2 ("If 143 is applied by a migrate.sh run", above).

  5. GATED with step 3: this entry's steps 3 and 3b. pm2 restart onchain-credit --update-env straight away, then apxUSD's series back to 2026-04-22: 0 failed, rows before block 24,943,407 read 1. Within five minutes the worker and the ingester each log [registry] reloaded …, and the worker logs … a coverage restatement pass starts now.

  6. The ingester (the coverage floor's step 2): no cycle error, scanned lines on every stream, no catch-up line naming a floor below 24,136,053.

  7. Read-only: the registry check (Saturn step 2, StakeWise step 2): exit 0, 13 class(es), 61 assertion(s) (code: 13 classes, 61 assertions, 7 of them Saturn's and 4 StakeWise's). Saturn's seven lines and StakeWise's four read ok; a moved on a report-only line is read before going on.

  8. Read-only, right before the sweep: B again.

    sql
    SELECT count(*) FROM onchain_credit.raw_events
     WHERE chain_id = 1 AND stream = 'escrow' AND block_number BETWEEN 24136053 AND 25828233;

    171,643 (prod, 2026-10-12). Only a sweep writes escrow rows that far below the live cursor; use the figure you read as B.

  9. GATED: one escrow sweep for both classes (Saturn step 3's two commands, --stream escrow --from 24136053 --to "$TO", dry run first). Keep the default 50,000-block window: pass no --window and set no BACKFILL_WINDOW (.env.local sets none (prod, 2026-10-12)). Then, read-only:

    • Saturn (its step 3's query): at least 1,740 requests, 1,722 processings, 1,637 claims and 3,378 ticket transfers, the first at block 24,836,599 (chain, 2026-10-12, to block 26,177,184).
    • StakeWise (its step 3's query): at least 91 requests (the first at block 25,067,970) and 86 claims (the first at block 26,034,764) (chain, 2026-10-12).
    • The stored count over the band's range (step 7's query): B + 5,117 = 176,760. Saturn's 5,116 are 1,082 requests, 1,041 processings, 955 claims and 2,038 transfers; StakeWise's 1 is the request at block 25,067,970 (chain, 2026-10-12). Any more means the sweep also filled rows of an older class: stop and read them before step 9.
  10. GATED: the escrow band, from the second provider (Saturn step 4's command, --stream escrow --to 25828233 --window 5000, with a note naming both classes). Dry run: measured 176760 … across 15 declared address(es) and address list: escrow 15 address(es) (code: 15 filter addresses; the 13 holding rows today are all among them). Then --confirm: recorded escrow=176760 over [24136053,25828233]. Run no escrow --verify between steps 8 and 9: the old band (171,643, no address list) counts every stored row and misses.

  11. GATED: the completion run, then --verify --stream escrow (Saturn step 5's two commands), with no --sample: from this release condition 3 draws only the newest record per block range (the pin section). For a repeatable re-check a pin can still be given: 25186053 (Stader, Apyx and Saturn logs) or 25036053 (StakeWise's one in-band log), both current only on the default window. Expect:

    • condition 1 176760 row(s) over [24136053,25828233] vs [176760,176760], with 0 stored row(s) on addresses in neither, not counted;
    • condition 3 drawn from 34 current sweep record(s), 35 superseded by newer overlapping ones not sampled(prod, 2026-10-12: 34 records on the 24,136,053 grid and 35 on the 22,527,558 grid overlap the band);
    • 11 coverage row(s) stamped live from 24136053, leaving 7 rows at 22,527,558 and 4 at 24,136,053 (the queue and the redeemer join the manager and the receipt);
    • verify PASS.
  12. After step 10 AND after the worker logs [restate] done: for the pass step 4 started: one re-derive list for both classes. Read-only, Saturn step 6's query and StakeWise step 6's query; the list is their union (a wallet on both is re-derived once). GATED: queue one whole-window rederive per wallet (the runbook's insert) and read each done. Then Saturn step 7 and StakeWise step 7 per wallet, and the two prod test wallets' regression check once.

  13. The first refresh-assets tick after step 3 (or a hand run, scripts/run-cron.sh refresh-assets.ts), read-only checks: sUSDat near 1.04 with both APYs NULL (sUSDat step 4); apyUSD near 1.44, with its APY once a day of rows exists, and apxUSD at the feed's value (1.0) with both APYs NULL (this entry's step 5); one [redemption-feeds] 1 published redemption value feed(s) checked, 0 finding(s) line.

  14. GATED: the two 45-day series fills, plan first: sUSDat's (sUSDat step 5: 181 boundaries, 0 failed) and apyUSD's (this entry's step 6: 0 failed). Either can run straight after the deploy instead, which shortens the time outage-block readings stay held.

  15. Read-only: the restatement checks. This entry's plan (step 4) first. Expect about 480 readings of 4 wallets, and 9 carried copies (prod, 2026-10-12, PR #1129's review): apyUSD 239 (wallet 130, morpho-blue 109) of 0x272c…, 0x5bc8… and 0xaae6…; apxUSD 127 (morpho-blue 63, wallet 58, escrow 6) of 0x272c… and 0x5bc8…; sUSDat 114 (wallet 70, morpho-blue 44) of 0x1929… and 0x5bc8…; copies 4 apyUSD, 3 apxUSD, 2 sUSDat; more only if those wallets wrote readings since. No held back … beside its own line (that means code from before PR #1129); a no redemption rate at its block hold is an archive outage at that block, retried each pass. Then, once the restatement pass and its re-derivations are done ([restate] done:, no rederive queued or running): sUSDat step 6 (no sUSDat reading left EXCLUDED except outage-held ones) and this entry's step 7, and the reconciler's book-overlays=0 for both plans' wallets.

  16. The coverage floor's steps 3 and 4, left over from v0.86.0, after step 10 and never before it:

    • (a) GATED, approved by Fred: the erc4626 one-window refresh in the coverage floor's step 4: the newest backfill record inside the band (F, T read at run time: 25827558, 25840566 (prod, 2026-10-12)). Expect [F,T] wrote 0 and range retained as raw evidence only.
    • (b) GATED: the erc4626 re-measure (the coverage floor's step 3), --to 25840566 --window 1000, hours. Dry run: measured 784903 … across 640 declared address(es) and address list: erc4626 640 address(es) (more if vaults were listed since). Then --confirm: recorded erc4626=784903 over [24136053,25840566].
    • (c) Read-only: the coverage floor's step 4. First --verify --window 1000 over every stream: escrow passes unpinned. Condition 3 may miss on a stale record, with conditions 1, 2 and 4 passing, on erc4626 (a record that was not refreshed), wallet-token and transfers (records taken over an older wallet or address set): record the wallet-token and transfers lines as they read and do NOT refresh them (Fred's approval covers erc4626 only). Then --verify --stream erc4626 --window 1000 --sample "$F": verify PASS. Expect erc4626 to read 784903 row(s) over [24136053,25840566] vs [784903,784903], 640 declared address(es) vs 640 measured, 0 declared since and 7793 stored row(s) on addresses in neither, not counted; escrow 176,760 over [24136053,25828233]; wallet-token N/N, one per enrolled wallet (15 on 2026-10-12 (prod)).
  17. Record executed: on all six entries (Saturn, StakeWise, sUSDat's book, this entry, 142 and the coverage floor), in one docs PR, each with its own lines; 142's and the coverage floor's continue their v0.86.0 records (PR #1118).

Run record, 2026-10-12 (v0.87.0, merge 1284e4c7). Every step ran in order, with #1124's 145 in step 3's run and its steps straight after it (the app restart of step 4 first, 13 s after the run, as 143 asks). Each entry's own record has the lines.

StepExpectedRead
0137 to 139 only; B 171,643; 9 escrow keys; erc4626 640/640, 784,903 of 792,696; both step 0sexactly; Saturn: 0x5bc81274…04c2 tickets_at_floor=1 tickets_now=0 (ticket 1330, claimed inside the window: named, not a stop), every other line 0/0; StakeWise all 0/0
1141 row; plan's sUSDat walletsthe row exactly; 114 readings of 0x1929d726…f45a (88) and 0x5bc81274…04c2 (26), 0 held back, 2 copies
2merge commit, deploy, health 200, three restarts17:10:33Z, run 38282474222 green, 0.87.0, health 200, all three restarted 17:11:53Z to 17:11:55Z
34 applied (here 5, with 145) and four row checks5 applied; the four rows exactly; 145's row and table
4restart, apxUSD fill 0 failed, reload linesrestart 17:12:54Z; 693 written, 0 failed; worker and ingester reloaded 17:16:56Z and 17:17:56Z, pass started
5no cycle error, scanned on every stream0; all 14 streams; no catch-up line
6exit 0, 13 class(es), 61 assertion(s)exactly; the 11 new lines ok
7B 171,643171,643
8Saturn ≥ 1,740 / 1,722 / 1,637 / 3,378; StakeWise ≥ 91 / 86; 176,7601,741 / 1,722 / 1,640 / 3,382 from 24,836,599; 91 / 86; 176,760 (8,662 new rows)
9measured 176760 … 15; recorded escrow=176760exactly
10condition 1 exact, 34 / 35, 11 rows, verify PASSexactly; 7 rows at 22,527,558 and 4 at 24,136,053
11union list re-derived; per-wallet checksone wallet (0x5bc81274…04c2), #2272 done; rows, reconciler and the test wallets clean
12sUSDat ~1.04, apyUSD ~1.44 with APY, apxUSD 1.0, [redemption-feeds] … 0 finding(s)1.045592; 1.44121 (APY 12.6%); 1; the line exactly
13both fills 0 failed181 and 181 written, 0 failed
14~480 readings of 4 wallets, 9 copies; no EXCLUDED; book-overlays=0480 / 4 / 9; none left; 0 for all four
15wrote 0; recorded erc4626=784903; every stream bar the stale three passes; pinned verify PASSexactly (the every-stream verify needed a longer statement timeout, the coverage floor's record)

Steps the floor or the new code refuse if run out of order:

  • the escrow band (step 9) before 142 is applied in step 3: the recorder's insert names measured_addresses;
  • an escrow --verify between steps 8 and 9: condition 1 is judged against the old band;
  • the coverage floor's step 4 before step 10: escrow's condition 4 misses with 2 declared address(es) not live from the floor: 0x…, 0x… (the queue's and the redeemer's keys have no coverage row until the completion);
  • a --sample 25186053 after a sweep on any other window: superseded … pin a current record;
  • any --from below 24,136,053.

Migration 155 (series verdicts) and the one-time re-judge of the stored rate history: prod steps, in order ​

  • belongs to: migration 155-series-verdicts.sql and scripts/repair/rejudge-series.ts (PR #1198, branch feat/series-data-quality), the release that ships them
  • mandatory: the release that ships migration 155 runs every step below, the prod re-judge included, before the release is declared done (Fred, 2026-10-19: the re-judge is part of that release, not a follow-up); node scripts/ci/release-steps-due.mjs and the release PR's check summary list it while it is owed
  • executed: 2026-10-19
  • run record: v0.95.0, release PR #1203, merge 673fd46774380223d38de185879dbe41350122dc; the owner explicitly authorized production and all accompanying server operations. Steps 0–8 completed before migration 154's outage recovery.

Production execution, 2026-10-19. The final staging candidate was 5839c5dc72553df634d8f13d985e4946dd51e51c. Its full release CI 39301841565 passed 9,302 unit tests, 273 fixture tests, 686 desktop interactions, 11 narrow-shell checks and 38 zoom checks. Independent release review converged on that head. Final real-data staging smoke 39300608905 passed 34 checks with 14 expected skips. Production deploy 39306116450 passed, health returned 200, and the app, ingester and worker restarted at 18:53:22Z–18:53:23Z.

The standard backup /opt/backups/creddit-2026-10-19T185450Z.dump completed at 18:57:46Z (2.0 GB), with pg_restore --list integrity verified, before release data writes. One migration-runner invocation applied exactly 154-history-recovery-items.sql and 155-series-verdicts.sql at 18:58:17Z. All nine named rate tables carry the verdict columns; incidents initially numbered zero. The broad information-schema query in step 3 returned 10 because the pre-existing token_price_bars_purge_810 backup also has rejected; the nine intended tables were checked individually.

The final-head staging dry run judged 605,233 readings and planned 45,123 changes. The production dry run judged 606,469 and planned 45,187, with migration 155 active and dry run: nothing written. Every table/rule and the total passed the stated tolerance:

Table / ruleStagingProductionAllowed differenceResult
aave_v3_reserve_apy / launch_window843846150PASS
fluid_dex_apy / launch_window1,1481,148150PASS
fluid_dex_apy / thin_pool23,27023,3131163.5PASS
fluid_ll_apy / launch_window1,8911,891150PASS
fluid_vault_rates / launch_window1,4081,408150PASS
morpho_market_apy / launch_window2,0242,024150PASS
pendle_market_state / launch_window1,7991,811150PASS
sparklend_reserve_apy / launch_window396396150PASS
token_basis / launch_window781781150PASS
token_yield_apy / dip_round_trip2,6572,657150PASS
token_yield_apy / impairment476476150PASS
token_yield_apy / launch_window6,6046,610330.2PASS
token_yield_apy / lump1,2191,219150PASS
token_yield_apy / non_finite9292150PASS
token_yield_apy / out_of_range515515150PASS
Total45,12345,1872256.15PASS

The execute command backed up every prior state to /root/rejudge-series-v0.95.0/rejudge-series-creddit-2026-10-19T185958702Z.jsonl, then printed wrote 45187 row(s) and history marked judged; 467 series axis baseline(s) fitted. The immediate whole-history verification judged 606,469 readings, planned zero changes and printed verify PASS: nothing left to change (exit 0). The first attended normal quality tick, under the refresh-assets lock with external notifications disabled, printed [series-quality] judged 16885 reading(s), 0 verdict(s) changed.

Read-only database/API spotchecks passed. The sUSDai readings from October 2 00:00 through October 3 12:00 UTC carry the restated 9.852535% 24h APY; October 3 18:00's separate 6.658395% observation remains unchanged. Fluid vault 168's first chart-eligible reading is June 19 00:00 UTC, and the value checksum of all 533 stored rate rows through October 19 18:00 UTC is unchanged (cb9f5ca26edc022a8edf92efb2edde3d). The Data quality register returned thin-pool flags and, through its normal pagination, rejected readings. Its public status API returned numeric judgedThrough; 1,209 baseline rows cover 467 series.

All 86 original non-finite APYs were compared with the row backup and remain preserved in the current value or restated_from, with their readings rejected. The planned restatements move eight original infinities to finite but still rejected out-of-range values and 14 finite raw values to rejected infinite annualizations, so the final 92 non-finite current values match the dry-run rule count; none is accepted. No original value became null. This check uses preservation of each original row, not an assumption that the count cannot change.

Server evidence is retained under /root/rejudge-series-v0.95.0/: backup.txt, migrations.txt, migration-checks.txt, staging-final-dry-run.txt, prod-final-dry-run.txt, execute.txt, verify.txt, first-quality-tick.txt, spotchecks-final.txt, and register-pagination.txt. Verification used database readers and APIs; no manual browser inspection is claimed.

What ships. Migration 155 adds rejected and reject_reason to the nine rate series, restated_reason and restated_from to token_yield_apy, one partial index per table on its flagged rows, and three tables with the app roles' SELECT, INSERT, UPDATE: series_quality_incidents, series_quality_baselines (each series' stored chart axis for the incident check) and series_quality_state (up to when the history is judged) (the schema). It writes no verdict: every stored reading starts accepted. It is additive, so staging auto-applies it and either order against the deploy is safe. Before it, the release's readers probe for the columns, find them absent and read every table as before; the series-quality step prints migration 155 is not applied: no verdicts written this tick; the admin register says the checks are not active yet; /api/series-quality/status answers null. After a code rollback the previous release never names the new columns, and its INSERTs get rejected = false. ADD COLUMN … DEFAULT false is a catalog change on Postgres 16; the nine partial indexes build in seconds on tables of 15k to 240k rows.

Why the re-judge is part of the release. The six-hourly step judges only its last eleven days. Every reading stored before the release has never been judged, and every reader would keep serving it: the impossible yield readings of the 2026-10-19 census (Clearstar Yield USDC at 1,000% to 298,000% for two months, yoETH's Infinity), sUSDai's -16.5% / +37% round trip on 2026-10-02, syrupUSDC's July 2024 to March 2025 sawtooth; and every chart would still draw each series' first 10 days. The re-judge also marks the history judged (the edge-marker label waits for it) and fills every series' stored axis (the incident check reads them).

Staging runs no refreshers (deployment), so no six-hourly tick ever judges staging's rows: its dry run is the whole history unjudged, as prod's is before step 5, and its series_quality_* tables stay empty. The nightly reseed restores prod's dump, which takes migration 155 away again until prod has applied it; a staging dry run then reads every row as accepted, which is the same starting point.

The staging dry run this release is compared against. Method: the re-judge's own dry run (scripts/repair/rejudge-series.ts, no flags), read only against staging on 2026-10-19, before 155 (every stored row read as accepted), under the rules as Fred settled them that day: no fee yield rejected for its size or magnitude, a thin-pool flag under $30,000, the 10-day chart window for every family. 605,233 readings judged, 45,123 changes:

TableRuleRows
fluid_dex_apythin_pool (flag, served)23,270
token_yield_apylaunch_window (flag, off the charts)6,604
token_yield_apydip_round_trip (restated)2,657
morpho_market_apylaunch_window2,024
fluid_ll_apylaunch_window1,891
pendle_market_statelaunch_window1,799
fluid_vault_rateslaunch_window1,408 (vault 168: 2026-06-08 to 06-18 18:00)
token_yield_apylump (restated)1,219
fluid_dex_apylaunch_window1,148
aave_v3_reserve_apylaunch_window843
token_basislaunch_window781
token_yield_apyout_of_range515
token_yield_apyimpairment476
sparklend_reserve_apylaunch_window396
token_yield_apynon_finite92

A rule names a change by its reason's first rule, so a rejection inside a launch window counts under the rejection. The restatements by series: iETHv2 2,293 (a dip's round trip; its 2023 to 2024 price moved with stETH almost daily), IPOR Liquity Carry 285 lumps and 177 round trips, ezETH 133 round trips, syrupUSDC 129 lumps, eUSDC-2 107, sUSDai 87 lumps and 17 round trips, rETH 70, syrupUSDT 59, fxSP 57, and 45 or fewer each on 30 more. The report prints the full list.

The order. Steps 0 and 4 to 8 run from the prod checkout (/opt/onchain-credit). Every command's output is kept in /root/rejudge-series-<release>/, the way the price re-judge kept its state, dump and logs in /root.

  1. Before the merge, read-only, on staging (the staging checkout at the release PR's final head, its rows prod's as of the last nightly reseed): the same dry run (step 4's command, with --list=0). It works with or without 155 on staging (the reseed takes it away, the staging deploy puts it back): without it the report says every stored row was read as accepted, which is prod's state before step 5 too. Keep its report: it is the comparison step 4 uses, and it is closer to prod than the table above, which ages with every day of history.
  2. The merge and the prod deploy, health 200, the app, ingester and worker restarted.
  3. The backup, with the standard backup runner, verified, before any write of the release.
  4. The migration, one scripts/ops/migrate.sh run as the owner; it applies 155 with any other file the release carries. Verify:
    bash
    sudo -u postgres psql -d creddit -Atc "SELECT count(DISTINCT table_name) FROM information_schema.columns WHERE table_schema = 'onchain_credit' AND column_name = 'rejected' AND table_name <> 'token_price_bars'"   # 9
    sudo -u postgres psql -d creddit -Atc "SELECT count(*) FROM onchain_credit.series_quality_incidents"                                                                                                    # 0
    If the release also carries migration 154's history recovery, run that recovery AFTER step 8, so this entry's dry run compares with staging's untouched. The recovery rewrites the 2026-10-18 yields and clears their verdicts; inside the eleven-day window the next tick judges them. If it runs later than 2026-10-29, follow it with step 5's command plus --tables=token_yield_apy and step 6.

Steps 4 to 8: the re-judge ​

  1. The prod dry run, read-only, in the same six-hour window as step 3 so the first tick has not yet judged the last eleven days:
    bash
    mkdir -p /root/rejudge-series-<release>
    (set -a; . ./.env.local; set +a; PGOPTIONS='-c default_transaction_read_only=on' \
      node_modules/.bin/tsx scripts/repair/rejudge-series.ts --list=40) | tee /root/rejudge-series-<release>/dry-run.txt
    It must NOT say migration 155 is not applied here, and must end dry run: nothing written. Compare it with step 0's staging report, per table and rule. The tolerance: each (table, rule) count within ±5% or ±150 rows of staging's, whichever is larger; no pair over 150 rows on one side and absent from the other; the total within ±5%. Staging and prod differ only by the rows written since the reseed and by any tick that judged the last eleven days first, so a difference beyond that means the two databases do not hold the same history. Against the table above (2026-10-19), expect history to have grown: thin-pool flags add about 60 rows a day, each newly listed series about 44 launch-window rows (about one series every two days), and the restatement counts move only with new dips and lumps. Outside the tolerance: stop, post both reports on the release PR and wait for Fred; the release is not done.
  2. Execute, with the guard against the wrong database (the app role holds UPDATE on the nine tables; no owner and no cron drain needed, since the six-hourly step writes the same verdicts and both are idempotent):
    bash
    (set -a; . ./.env.local; set +a; node_modules/.bin/tsx scripts/repair/rejudge-series.ts \
      --execute --confirm-db=creddit --backup-dir=/root/rejudge-series-<release>) | tee /root/rejudge-series-<release>/execute.txt
    It writes every changed row's prior state to /root/rejudge-series-<release>/rejudge-series-creddit-<stamp>.jsonl (fsynced) before the first write, prints the path, then wrote N row(s), then history marked judged; N series axis baseline(s) fitted. A restated yield also keeps its first-written value in restated_from, so every restatement is reversible from the row. Numeric prior states are stored as PostgreSQL numeric text in the backup, including Infinity, -Infinity and NaN; these must never become JSON null. A verdict alone leaves the stored yield value untouched. The repair and the six-hourly judge preserve non-finite values while rejecting them, so a following verification keeps that rejection.
  3. Verify:
    bash
    (set -a; . ./.env.local; set +a; node_modules/.bin/tsx scripts/repair/rejudge-series.ts --verify) | tee /root/rejudge-series-<release>/verify.txt
    It must print verify PASS: nothing left to change (exit 0). A tick between steps 5 and 6 can only have judged new readings; if it reports a handful, run step 6 again after it. Run any time later, --verify can list a few impairment readings of a share price that has kept falling for weeks with a different start time in their reason: the dip walk's anchor depends on where a tick's window begins. They are rejected either way and no number moves (docs/data-pipeline.md#series-quality); right after step 5 there are none.
  4. Spot-check, read-only: /admin's Data quality register lists the newest rejections and thin-pool flags; the sUSDai 24h APY on 2026-10-02 to 03 reads the restated 9.85%; Fluid vault 168's chart on Carry Trades starts at 2026-06-19 00:00 while its row figures are unchanged; curl -s http://localhost:3001/api/series-quality/status returns a judgedThrough number; and sudo -u postgres psql -d creddit -Atc "SELECT count(*) FROM onchain_credit.series_quality_baselines" is at least the number of series.
  5. Record it here, then the release is done: set executed: to the date (the status alone on that line) and add a - **run record:** line under it with the release, the migration run, step 0's and step 4's counts per table and rule side by side, the wrote N row(s) and history marked judged lines, the backup path, the verify PASS line and the first tick's [series-quality] lines.

Undo, if it is ever needed: replay the backup's before states through the same UPDATE … FROM jsonb_to_recordset shape applySeriesPlan uses; --verify then reports the re-judge as owed again.

One-time repairs and rebuilds (gated) ​

Each of these is a prod write that needed explicit approval before it started. None is part of any standing procedure, and none is re-runnable for effect: they restate rows the chain has since settled differently. Ordered as the releases that needed them shipped.

The quarantine: one wallet never holds the tick cursor (issue #981, no migration): prod steps, in order ​

  • belongs to: issue #981, PR A (plan S8c, Fred's ruling of 2026-10-04); no migration
  • executed: 2026-10-05

What it changes for a user, in one line: a wallet whose 6-hour update falls short twice in a row stops holding everyone else's history back; its own page reads as partially measured (returns after the stretch it is missing are not measured, holdings and values still shown) until it catches up in one step, and the team is paged in words while it is set aside.

No migration, no backfill, no data step. The quarantine's state is the queue's own rows and the wallet's existing pending marker. The deploy restarts the worker (as every deploy does), and its first settlement after the deploy applies the rule. The steps, on the prod box only (staging runs no tick and no standing worker, so it has nothing to page):

  1. LEDGER_QUARANTINE_AFTER_SWEEPS (optional). Unset means 2 (the default, and the recommendation): a wallet is settled past at its second partial sweep in a row. Set it in /opt/onchain-credit/.env.local only to change N (a whole number, at least 1; anything else reads as 2). Both the worker and the paging job read it; restart the worker after changing it (pm2 restart creddit-ledger-worker).

  2. Run the paging job once by hand, after the deploy is green. It reads the queue and writes one row, its run stamp (portfolio:worker:quarantine-page, which the hourly check reads). On a population with no quarantined wallet it prints ledger-quarantine: ok, no wallet set aside from the 6h sweep (after 2 partial sweeps) env=onchain-credit and exits 0:

    bash
    cd /opt/onchain-credit && scripts/run-cron.sh check-ledger-quarantine.ts; echo "exit=$?"
    tail -n 3 /tmp/onchain-credit-cron/onchain-credit-check-ledger-quarantine.log

    An exit of 2 means a wallet is quarantined already (its sweep has been partial twice in a row since before the deploy, or the first settlement after it released one): the message went out; read it, and the worker's [worker] sweep … every one a quarantined wallet's line.

  3. Add the crontab line (prod only), from a file, and count it:

    bash
    crontab -l > /root/crontab.quarantine-$(date -u +%Y%m%dT%H%M%SZ)
    # append: 20 1,7,13,19 * * * /opt/onchain-credit/scripts/run-cron.sh check-ledger-quarantine.ts
    crontab -l | grep -c '/opt/onchain-credit/scripts/run-cron.sh check-ledger-quarantine.ts'   # 1
  4. Watch the first tick after the deploy (:50) and the job's run at :20 past the next hour: the sweep's [worker] sweep … -> done lines and v2 tick cursor -> …; a sweep holding one wallet's partial reads … not done, so the tick cursor is NOT advanced … (not released: 1 wallet(s) not quarantined yet …) the first time and … every one a quarantined wallet's … the second. Record the lines here with the date in executed:.

Executed 2026-10-05 (v0.77.0, release PR #1021 (head release/v0.77.0, cut from staging at da447268), merge 63ce93ba, tag v0.77.0, deploy run 37292432839: Deployed 63ce93ba at 2026-10-05T09:49:22Z, the app, the ingester and the worker online on 0.77.0, the app 200), summary lines per step. Before the deploy every wallet's newest sweeps were done (the 06:50Z, 00:50Z, 18:50Z and 12:50Z ticks, three wallets each) and no …:jit-pending marker existed, so no wallet could be quarantined at the first settlement. Step 1: LEDGER_QUARANTINE_AFTER_SWEEPS not set (default 2). Step 2 at 09:49:44Z: ledger-quarantine: ok, no wallet set aside from the 6h sweep (after 2 partial sweeps) env=onchain-credit, exit 0; the run stamp portfolio:worker:quarantine-page written at 09:49:45Z (block 0). Step 3 at 09:49:49Z: crontab backed up to /root/crontab.quarantine-20261005T094949Z (41 lines), the line 20 1,7,13,19 * * * /opt/onchain-credit/scripts/run-cron.sh check-ledger-quarantine.ts appended (42 lines), count 1. In the first hour: no failed job, no partial sweep. Owed (step 4): the first tick after the deploy (12:50Z) and the job's first scheduled run (13:20Z).

What the deploy itself changes, beside the page. The hourly ingester check's derive-lag arm stops paging a set-aside wallet's pageable: partial while the quarantine page has run within 7 hours (before step 3 it keeps paging it); a partial sweep job's reason gains ; positions: …; a done sweep job that absorbed its wallet's marker re-queues the audits of the readings over the stretch it derived; the summary route flags a set-aside wallet's two cumulatives withheld; and the tick vetoes the certificates of a set-aside wallet whose marker lies inside the pass it notes. No wallet that is not set aside has a served number or a certificate move.

Rollback. FIRST remove the crontab line, so no run lands between the revert's deploy and the edit (the old checkout has no check-ledger-quarantine.ts and would page MODULE_NOT_FOUND): crontab -l | grep -v 'check-ledger-quarantine.ts' > /tmp/ct && crontab /tmp/ct, and count 0. Then revert the release commit on main; the deploy restarts the app, the ingester and the worker on the old code. Nothing to undo in the database: no migration; the page's run stamp row is left (the old code never reads it; DELETE FROM onchain_credit.chain_scan_cursors WHERE chain_id = 1 AND scope = 'portfolio:worker:quarantine-page' if wanted). A wallet quarantined at the moment of the rollback keeps its pending marker, so nothing it owes is lost: the old code's next sweep in which it is still partial holds the tick cursor again (the old behaviour, which the derive-lag arm pages hourly as a pageable partial and, after 12 hours, as a stalled cursor), and its first clean sweep absorbs the marker and derives the whole stretch, as before. Its page goes back to the old reading of that stretch (returns booked over it, the "Updated" time held below the marker), and the reasons already stored with ; positions: … are text the old code ignores.

GATED STEP: relabel the receipts stranded below the tick cursor (#777) ​

  • belongs to: the #777 settle-line release (v0.53.0)
  • executed: unverified

Prod held zero users after the full wipe of 2026-09-10 (docs/plans/pt-coverage-811-plan.md §0), so this step has had no population to act on since that date. That is not the same as having run: confirm against prod before deciding it is finished.

Run once, on prod, after the release that carries the settle-line fix, and only there (staging reseeds from prod's dump nightly, so a repair applied to staging is gone by morning). It is one UPDATE. It changes no amount, no quantity and no valuation — only the confidence label a movement is shown with.

What it repairs. Until this release the composition judged a row's basis against the top of the range it was handed rather than against the writer's own settle line, so each 6h tick wrote roughly 48 to 64 blocks of receipts as provisional below the cursor it then saved. Nothing re-derives below a cursor, so those rows kept that label for ever, and the Activity feed renders provisional as Confirming and withholds the stated total of any group containing one. The fix stops new rows landing there; it cannot reach the rows already written.

Read it first — the query is the issue's own (#777):

sql
SELECT count(*) AS stuck_provisional, min(block_number), max(block_number)
  FROM onchain_credit.portfolio_flow_events_v2
 WHERE chain_id = 1 AND basis = 'provisional'
   AND block_number <= COALESCE(
         (SELECT last_scanned_block FROM onchain_credit.chain_scan_cursors
           WHERE chain_id = 1 AND scope = 'portfolio:v2:tick'), -1);

COALESCE(…, -1) is load-bearing on a box whose first tick has not run yet: the scalar subquery is NULL there, block_number <= NULL is NULL, and the query would report a clean zero for the wrong reason. With the fallback it reports zero because the bound is below every block, which is the same answer honestly arrived at. Expect a count in the low thousands per month of history on a tracked population, with max(block_number) at or just under the current cursor.

Then write. Every row it touches is at or below a cursor the tick advanced only over finalised blocks, so it is settled by construction:

sql
UPDATE onchain_credit.portfolio_flow_events_v2
   SET basis = 'live'
 WHERE chain_id = 1 AND basis = 'provisional'
   AND block_number <= COALESCE(
         (SELECT last_scanned_block FROM onchain_credit.chain_scan_cursors
           WHERE chain_id = 1 AND scope = 'portfolio:v2:tick'), -1);

Re-running is a no-op (the predicate no longer matches). It is safe beside a live tick: the tick's own writes land strictly above the cursor this statement bounds on, and the merge restates rows on their primary key rather than reading basis back. Nothing needs to be stopped for it.

Verify by re-running the count above (zero), and on /portfolio's Activity feed: a group whose total previously read "One movement here is still confirming beside a settled one, so no total is stated yet" now states its amount. A band of genuinely recent movements — the ones above the cursor, which the next tick re-derives — correctly keeps the Confirming tag.

GATED STEP: the Fluid tick-padding re-mark ​

  • belongs to: the Fluid tick-padding fix (v0.53.0)
  • executed: unverified

Prod held zero users after the full wipe of 2026-09-10 (docs/plans/pt-coverage-811-plan.md §0), so this step has had no population to act on since that date. That is not the same as having run: confirm against prod before deciding it is finished.

Runs once, on prod, after the release that carries it, and only there: staging reseeds from prod's dump nightly, so a repair applied to staging is gone by morning. It restates every stored Fluid debt-leg snapshot from the position's net borrowing, dropping the dustBorrow tick padding the wallet does not owe (M14, The tick padding).

Dry-run first, always. The dry-run is read-only, prints the read plan before it issues a single chain call, and names every row it would touch.

Through run-cron.sh, like every other scripts/repair/* job, and not with a bare npx tsx: the wrapper is what sources .env.local, takes the per-script single-flight lock, honours the deploy-window toolchain guard and writes the [fail] line the cron alert greps. It appends every run to /tmp/onchain-credit-cron/onchain-credit-remark-fluid-dust-debt.log, so that is where the dry-run's report is read, not the terminal.

bash
cd /opt/onchain-credit                  # ETHEREUM_ARCHIVE_RPC_URL must be in .env.local:
                                        # a historical position read needs an archive node

# 0. size the run without paying for it
scripts/run-cron.sh repair/remark-fluid-dust-debt.ts --plan-only

# 1. the dry-run: every row, every delta, every skip class
scripts/run-cron.sh repair/remark-fluid-dust-debt.ts

# 2. write
scripts/run-cron.sh repair/remark-fluid-dust-debt.ts --execute

# the report of each of those runs:
tail -n 80 /tmp/onchain-credit-cron/onchain-credit-remark-fluid-dust-debt.log

Judge the run against its OWN derived population, never against a number on this page. The corpus moves on its own, and it has moved twice in 24 hours: one Fluid borrowing is still open, so the 6h refresher adds a padded row to that leg on every tick until the release lands, and a tracked wallet's historical backfill can write the first snapshot of a leg nobody had seen before (that is exactly how a fifteenth leg and a fifth wallet appeared on 2026-09-02). Every count in the run is therefore derived by the script from the rows that exist at the moment it runs, and the judgement is made on the shape and on those three lines reading consistently:

  1. --plan-only prints the scope it derived (rows, legs, wallets) and the reads it will pay for;
  2. the dry-run prints would repair N rows on M legs, the per-leg padding in bp, and every skip class on one line, skipped: unparseable=… no-read=… no-leg=… unrecognised=… already-net=… no-amount=…;
  3. --execute prints executed: N rows updated.

Read them against each other, then against the reconciler's own before and after. The --plan-only and dry-run scopes must agree; executed: N must equal the would repair N of the dry-run immediately before it; and a second dry-run after the write must classify every row it just wrote already-net and report would repair 0 rows (the repair is idempotent).

STOP conditions. All of them are shape, none of them is a count (report, and do not proceed):

  • a leg outside the Fluid debt class on the scope line. Everything in scope is a fluid:vault:…:debt key, so anything else means the scope reached rows it must not.
  • unrecognised above 0. That is a stored quantity the script could not reproduce as borrow + dust, so it was refused rather than rewritten. A refusal is the script saying a row was not written by the convention this repair reverses.
  • unparseable above 0: a stored key the repair cannot name at all.
  • no-read, no-leg or no-amount above 0. Every row in scope sits far above the pinned resolver's deployment, so a withheld read is new information, not routine.
  • any positive delta. A debt leg can only shrink when the padding comes off.
  • per-leg padding outside the vault's tick spacing (roughly 0 to 15 bp of gross debt). The padding is one tick; a leg quoting more than a tick is not padding.
  • executed: differing from the would repair line of the dry-run immediately before it.

already-net is the one class expected to be non-zero: it counts whatever the live 6h refresher wrote net between the release landing and the run, and those rows are correct and left alone. No skip is ever written as a zero. A row the script cannot reproduce as the old convention is refused (unrecognised), and a positionByNftId that does not land is withheld (no-read); neither is guessed at, which is why a non-zero count in either class is information rather than noise.

Illustrative only, measured read-only on 2026-09-03, and stale by design: 316 rows across 15 legs and 5 wallets, costing 234 positionByNftId reads; sum |delta value_market| around 10,050 and every delta negative, with per-leg padding running 0.83 bp (NFT 18415) to 13.77 bp (NFT 17423) of gross debt. The same measurement read 307 rows / 14 legs / 4 wallets / 225 reads / 5,861.67 the day before. These figures are here to say what the output looks like, not to be matched: the run's real ones come from its own --plan-only line, which is correct by construction.

What it deliberately does not touch, and why that population is a DIFFERENT SET.portfolio_flow_events_v2 carries the same convention in to_balance (and in qty_delta on the state-read rows the venue witnesses). Those rows are DERIVED, so they are corrected by a ranged re-derivation, never patched. They are also not the legs the re-mark can see: a snapshot row exists only where the 6h refresher or a backfill read the position, while a v2 flow row exists wherever the wallet's Fluid receipts were derived. A wallet whose Fluid borrowings are all closed can therefore keep every one of its ledger rows while holding no Fluid snapshot for the re-mark to find, and which legs are in that state changes whenever a backfill runs.

Both populations move, and the gap between them moves independently of either. Illustrative, measured read-only on 2026-09-03: the ledger holds 39 rows on 16 legs across 5 wallets, 24 of them carrying a non-zero to_balance (a live borrowing, and so that block's padding), against a re-mark scope of 15 legs on 5 wallets, with exactly one leg unseen (nft:18380 on wallet 0x5d09098f…, 3 rows of which 2 carry a balance). The day before, two legs were unseen: the same wallet's nft:17764 had no snapshot until its historical backfill wrote seven, which moved that leg into the re-mark's own scope without moving the ledger's counts at all. Whatever the split is on the day, those padded ledger rows are served numbers, and the padding at a leg's last mark before its close is what lands as the phantom exit gain this whole step exists to remove: $460.27 on NFT 17764 (4.48 bp of gross debt at block 25,191,053) and $408.10 on NFT 18380 (14.16 bp at 25,392,968), against the $202 that opened the finding. On 2026-09-03 the first of those sits inside the re-mark's own scope and only the second is unseen; read the run's own list rather than assuming that split.

So step 3 is scoped from the LEDGER, never from the re-mark's own output and never from this page. The script prints that population on every run, --plan-only and a refusal to run included (it costs two SELECTs and no chain read): the row, leg and wallet counts, every leg the re-mark itself cannot see, the wallet list, and the command below with its --to already filled in. Take the --to from the LAST run of the script, which is the dry-run whose write you have just accepted, and run the build unscoped (no --wallet: narrowing the build to one wallet is what leaves another one padded). That run's wallet list scopes nothing; keep it to check afterwards which wallets moved. Only rows written before the release can be padded at all (after it the live writers use the fixed reader), so a bound taken from a run made after the release reaches every row that needs re-deriving, and re-deriving the net ones costs nothing.

bash
set -a; . ./.env.local; set +a          # the builder is not a cron job: it needs the env here
# 3. re-derive, RANGED (a bare sweep resumes cursors and derives nothing) and UNSCOPED.
#    The bounds below are ILLUSTRATIVE (2026-09-03): copy the command the LAST run printed.
npx tsx scripts/build-shadow-ledger.ts --from 24136053 --to 25859296
# 4. then the reconciler, and re-state the acceptance figures

--to is max(recorded arm block, highest Fluid debt ledger row), and the arm block by itself is not enough. The re-derivation trigger derives [floor, arm_block] and the derive cursor is a GREATEST upsert, so nothing ever revisits a row written above the arm. That costs nothing only while the highest Fluid debt row sits below it (25,847,926 against an arm of 25,859,296, both still true on 2026-09-03), and NFT 19028 is still open: one operate before the release puts a padded row above the arm that neither this step nor the live writers would ever correct. The script computes the bound from the data, so the printed command is right even on the day that happens. If the bound it prints is above the arm, let that block finalize before the build runs: the history build declares the settled basis and writes no provisional row, so a range reaching into the unfinalized window would leave the reorg repair no handle on the rows it rewrites there.

Step 3 is the same command the Fluid opening-day step runs, and that step is the one that owns the expectations for it: it is scoped from the same ledger, over the same wallets, with the same bound. Where both are outstanding, run this one first and read the two sections' expectations together — the ranged build restates the debt marks AND lands the birth markers in one pass, so neither section's "what moves" list is complete on its own.

GATED STEP: mark the Fluid births, so a loop's opening day is on the books ​

  • belongs to: the Fluid opening-day fix (v0.53.0)
  • executed: unverified

Prod held zero users after the full wipe of 2026-09-10 (docs/plans/pt-coverage-811-plan.md §0), so this step has had no population to act on since that date. That is not the same as having run: confirm against prod before deciding it is finished.

Runs once, on prod, after the release that carries the opening-day fix (issue #739, PR #792), and only there: staging reseeds from prod's dump nightly.

Run it AFTER the Fluid tick-padding re-mark, never before, and after that section's own step 3 — the ranged ledger re-derivation it defers the debt marks to. The command below is the same ranged unscoped build, so if the padding step's ledger half has not run, this build restates the Fluid debt marks as well and the "only meta moves" expectation below is simply false. Check that first; if both are outstanding, the expectations are the padding step's plus this one's, not this one's alone.

What it repairs. A Fluid position's opening movement carries two quantities that are struck against different things: the amount the venue's event names, and the balance the venue itself reports at the end of that block. On a borrowing they are not the same number — the vault rounds the drawn debt up to a price tick, and on a two-token position the balance is struck at the pool's composition. The reader used to decide whether a holding was brand new by comparing those two, so a rounding of a billionth of the position made it conclude the holding pre-existed: it invented a balance for every day before the position was created, marked all of them unvaluable, and reported nothing for the opening day itself. The venue publishes the creation (NewPositionMinted), so the derivation now stamps that fact into meta on each leg's opening row and the reader answers from it. Nothing else in the ledger changes.

Part of this lands at DEPLOY, ahead of this step, and that is expected. The second half of the fix — a two-token position's opening day reported at position scope — reads the same "did this leg exist" question, and for a position all of whose pool-token legs have agreeing quantity columns the arithmetic already answers it without any marker. Exactly one position on prod is in that state: 0xef08c6a4…'s NFT 18415. Its ETH-book day cell 2026-06-27 → 06-28 moves from 0 to about −0.055 total return / +0.003 accrual the moment the release deploys, and to about −0.034 / −0.017 after this step adds its debt leg. Take that wallet's "before" ETH figures from a measurement made before the release, or a correct repair reads as a failed one.

The earlier "expected 4" was one wallet's legs mistaken for the corpus. Issue #739 and PR #792's original body both said this step removes exactly four W1 unread-endpoint rows, naming NFTs 17548, 17549, 18415 and 17671. All four are 0xef08c6a4…'s. The real population is every Fluid wallet, and on 2026-09-05 that is 5 wallets, 14 positions, 35 legs, of which 11 carry the positive difference that produces a W1. Derive the population from the ledger on the day, and do not re-derive that error from this page: every count below is stated so it can be checked leg by leg, and the queries are the authority.

1. Scope and size it from the ledger, read-only, before anything else.

sql
-- every Fluid leg whose opening row's two quantity columns disagree. A POSITIVE difference is a
-- W1 carrier (the leg reads as occupied before it existed); a NEGATIVE one already reads as
-- unoccupied and files no W1, but its at-entry basis still moves. On 2026-09-05: 11 positive,
-- 10 negative.
WITH first_row AS (
  SELECT DISTINCT ON (wallet, position_key)
         wallet, position_key, block_number, qty_delta, to_balance
    FROM onchain_credit.portfolio_flow_events_v2
   WHERE chain_id = 1 AND venue = 'fluid'
   ORDER BY wallet, position_key, block_number, log_index, seq
)
SELECT wallet, position_key, block_number,
       to_balance - qty_delta AS fabricated_pre_birth
  FROM first_row
 WHERE to_balance IS DISTINCT FROM qty_delta
 ORDER BY (to_balance - qty_delta) DESC;

-- the wallets to re-derive: every wallet with a Fluid vault position, not only the carriers
SELECT DISTINCT wallet FROM onchain_credit.portfolio_flow_events_v2
 WHERE chain_id = 1 AND venue = 'fluid' ORDER BY 1;

-- the upper bound, from THIS population
SELECT GREATEST(
         (SELECT last_scanned_block FROM onchain_credit.chain_scan_cursors
           WHERE chain_id = 1 AND scope = 'portfolio:v2-campaign:arm-block'),
         (SELECT max(block_number) FROM onchain_credit.portfolio_flow_events_v2
           WHERE chain_id = 1 AND venue = 'fluid')
       ) AS to_block;

Re-take the bound immediately before the run. A Fluid position minted between the query and the build lands above --to and stays unmarked, and the derive cursor is a GREATEST upsert so nothing ever revisits it. If the bound the query returns sits above the arm block, let that block finalize first, for the reason the padding step gives. On 2026-09-05 the highest Fluid row was 25,847,926 against an arm of 25,859,296, so the bound was the arm; the ledger's highest row over all venues was 25,904,143, and leaving those above --to costs nothing because no non-Fluid row can carry the marker.

It is a multi-hour campaign holding PORTFOLIO_WRITE_LOCK_SQL. Drain the portfolio cron first, as the other from-the-floor steps on this page do, and plan for the wall clock of a full replay over every Fluid wallet rather than a tick.

2. Re-derive, RANGED and UNSCOPED. Ranged because a bare sweep resumes cursors and derives nothing; unscoped because narrowing to one wallet is what leaves another one unmarked, and re-deriving a wallet the marker does not touch costs nothing.

bash
cd /opt/onchain-credit
set -a; . ./.env.local; set +a          # the builder is not a cron job: it needs the env here
npx tsx scripts/build-shadow-ledger.ts --from 24136053 --to <to_block, re-taken now>

3. Acceptance — shape first, and every count checkable leg by leg.

  • No row is added and none is deleted. meta is the only column that moves (plus updated_at), given the precondition above. A changed row count means something else moved and is a stop.

  • One marked row per Fluid leg — every Fluid position on prod has a NewPositionMinted inside the range, so the count is the leg count, 35 on 2026-09-05:

    sql
    SELECT wallet, count(*) AS marked_legs
      FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND venue = 'fluid'
       AND meta @> '{"birth": true}'::jsonb
     GROUP BY 1 ORDER BY 1;

    and it is on each leg's first row only: re-run query 1 and confirm no later row of the same leg carries it. The predicate is a containment test rather than a cast, deliberately — a cast reads the string "yes" as true.

  • W1 unread-endpoint falls by exactly 9, and no new W1 appears anywhere. The count is engine output, not a column, so it comes from the read-only reconciler (below). The nine are all debt legs: 17548 GHO, 17549 GHO, 18415, 17671 (0xef08c6a4…); 17303, 17438, 17423 (0xe1590894…); 17764, 18380 (0x5d09098f…). A tenth, or a different leg, is a stop. Two of the eleven positive carriers deliberately do not move: NFT 18348 (0xaae6ae86…) sits in an EXCLUDED book, where a leg books 0 under a coverage note and files no withhold at all; and NFT 19028 (0xb2ee508c…) was minted before that wallet's first snapshot, so it has no pre-birth interval to withhold. "No new W1" is measured rather than hoped: every one of the eleven is read by the spine at every grid point it is held at, so none acquires a later stretch.

  • W9 ghost-row stays 0. This is the one hazard the change creates rather than removes: a leg's pre-birth points now read as ledger-empty, so a spine row at such a point would become a ghost. None exists — checked directly, zero snapshot rows precede any of these legs' births — and the budget is zero, so a single row is a stop.

  • W4 unresolvable-composition keeps its row count; its BIRTH rows move from unreconciled to attributed, joining the closes. No withhold shape appears that was not there before.

  • The at-entry basis and the vintage move on all 21 disagreeing legs — the 11 positive and the 10 negative — and that is expected, not the stop condition. Each stops having its at-entry basis reconstructed from the first snapshot the leg appears in and starts having it read off the opening movement, and its "since" date moves from that snapshot to the mint. That is the position row's at-entry column and the left-hand side of its secondary-market dislocation P&L. Measured on 0xef08c6a4…'s May pair: −3.8599 → −16.7786, −3.2215 → −5.7567, −4.5241 → −0.1632, −3.7449 → −6.3931, vintages 05-12 00:00 → 05-11 19:25 / 19:35. A leg outside query 1's list whose at-entry column moves IS a stop.

    sql
    -- the legs whose at-entry basis stops being reconstructed: query 1's set, said the other way
    SELECT wallet, position_key
      FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND venue = 'fluid'
       AND meta @> '{"birth": true}'::jsonb
       AND to_balance IS DISTINCT FROM qty_delta
     ORDER BY 1, 2;
  • These day cells move, and no others. Each is the interval containing a position's birth. A cell outside this table is a new shape and a stop.

    walletbookcelldriver
    0xef08c6a4…ETH2026-06-27 → 06-28NFT 18415 — partly at deploy, see above
    0xef08c6a4…USD2026-05-11 → 05-12NFTs 17548 + 17549; books −17.81 / +35.68, the close stays −15.19 / −0.73, and the pair's life foots to +26.48 / +32.10
    0xef08c6a4…USD2026-05-17 → 05-18NFT 17671
    0xe1590894…USD and ETH2026-04-29 → 04-30NFT 17302 (USD) and NFT 17303 (ETH)
    0xe1590894…USD and ETH2026-05-06 → 05-07NFT 17423 (USD) and NFT 17438 (ETH)
    0x5d09098f…USD2026-05-21 → 05-22NFTs 17764 + 17761
    0x5d09098f…none — the leg has no snapshot row2026-06-25 → 06-26NFT 18380
    0xaae6ae86…EXCLUDED—nothing moves
    0xb2ee508c…——nothing moves

    The list is wider than query 1's leg list on purpose: a two-token position's birth cell also moves where its own opening rows agree, because the position-scope reporting is what changed there. 0xe1590894…'s lifetime figures for NFT 17302 should land at −21.48 / −2.66 and for NFT 17423 at +50.06 / +86.70.

  • A Fluid position minted AND unwound between two grid points reconciles rather than paging. The reader files nothing at position scope there — the day's total is right, but the shares a joint figure would be split by are unobservable at both ends of that day — and the guard that makes it file nothing is what keeps the reconciler from throwing. No such two-token position exists on prod today (the three positions whose whole life sits inside one interval all have a single-token shape), so this is protection against the first same-day loop rather than a live fault. Confirm it anyway: a [fail] … the engine filed 0 rows for 1 inputs means the guard did not land.

    sql
    -- read-only. Any row with grid_pts_inside_life = 0 AND smart_legs >= 2 is the shape.
    WITH life AS (
      SELECT wallet,
             split_part(position_key,':',1)||':'||split_part(position_key,':',2)||':'||
             split_part(position_key,':',3)||':'||split_part(position_key,':',4)||':'||
             split_part(position_key,':',5) AS scope,
             count(DISTINCT position_key) FILTER (
               WHERE array_length(string_to_array(position_key,':'),1) >= 7) AS smart_legs,
             min(ts) AS born, max(ts) AS last_row
        FROM onchain_credit.portfolio_flow_events_v2
       WHERE chain_id = 1 AND venue = 'fluid'
       GROUP BY 1,2)
    SELECT l.wallet, l.scope, l.smart_legs,
           (SELECT count(DISTINCT s.snapshot_ts) FROM onchain_credit.portfolio_position_snapshots s
             WHERE s.chain_id = 1 AND s.wallet = l.wallet
               AND s.snapshot_ts > l.born AND s.snapshot_ts < l.last_row) AS grid_pts_inside_life
      FROM life l ORDER BY 4, 3 DESC;
  • Reconciler, read-only — this is also where the W1 and W4 counts come from. Without --marker the run writes nothing at all:

    bash
    cd /opt/onchain-credit && DATABASE_URL="$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)" \
      npx tsx scripts/ops/reconcile-ledger.ts

    Zero identity failures at leg and book scope, zero roll-up skips, zero unshaped declines. The withhold budget must be re-set from this run rather than carried forward: nine legs lose their pre-birth stretches and the W4 birth rows begin pricing a real joint residual, so the before and after numbers are not comparable.

  • Ghost adjudicator, read-only: npx tsx scripts/ops/adjudicate-ghost-rows.ts — ledger-hole and spine-stale at their standing values and no new ghost.

No migration. No new table or column — the marker rides in meta, which every row already has, and the reader projects it from columns that exist today. The code is inert until the data lands for every position except NFT 18415, named above, so there is no window in which new code meets old data in a broken state.

GATED STEP: re-derive every wallet that holds a fixed-rate principal token ​

  • belongs to: the #767 principal-token wallet-leg fix (v0.54.0)
  • executed: unverified

Prod held zero users after the full wipe of 2026-09-10 (docs/plans/pt-coverage-811-plan.md §0), so this step has had no population to act on since that date. That is not the same as having run: confirm against prod before deciding it is finished.

Runs once, on prod, after the release that carries the principal-token repair, and only there: staging reseeds from prod's dump nightly.

Read this first: the release itself already moves one account's published figure, before you run anything. The repair has two halves and they land at different moments. The debit — the wallet's principal-token holding losing what it posted as collateral — is derivation-side and waits for the run below. The bridge guard is read-path: it runs inside the engine every time the page is served, so the moment the release deploys it declines the phantom on 0x5d09098f…'s dollar chart and the account's served lifetime jumps by the declined amount. Measured read-only on the 2026-09-03 rows, that account moves from about minus $4,541,714 before the release to about plus $417,133 at deploy, and its charted-nowhere curve from about plus $1,019,624 to about minus $90,239. Nothing else in the corpus moves and no accrual figure moves anywhere.

That intermediate is not a halfway house: the guard declines the minus $4.96 million leg of the phantom pair and leaves its plus $380,932 mirror standing, so between deploy and this run the account publishes roughly plus $417k of lifetime return on about $1.5M of equity where the honest figure is about plus $31k. Take the "before" figure from a measurement made BEFORE the release, not from the page after it, and expect the observed move across this step to be downward — about minus $386k — rather than the plus $4.573M restatement measured against the pre-release ledger. An operator judging this step against the pre-release number after deploy reads a correct repair as a failed one.

Every number this step is judged on is derived by a query at the moment you run it. A pre-written count made a correct repair look like a stop condition once already, so the checks below are identities between two populations the database itself produces.

1. Scope it from the ledger, not from this page.

sql
-- read-only; run before anything else and use ITS output as the wallet list
SELECT DISTINCT wallet
  FROM onchain_credit.portfolio_flow_events_v2
 WHERE position_key LIKE 'pendle:pt:%'
 ORDER BY 1;

2. Take the upper bound from the ledger too, and from THIS population. --from is the derivation floor 24136053, a constant of the system that the run refuses to go below (exit 2). --to is max(recorded arm block, the highest ledger row on the wallets step 1 returned). That is not the pair the Fluid re-mark step above prints: that script computes max(arm, highest FLUID DEBT row), which is Fluid-scoped by construction and sits below the arm today, so copying its command lands on a bound that is too low. Nothing else prints the right bound for this population, so derive it:

sql
-- read-only; its single value is the --to below
WITH pt_wallets AS (
  SELECT DISTINCT wallet FROM onchain_credit.portfolio_flow_events_v2
   WHERE position_key LIKE 'pendle:pt:%'
)
SELECT GREATEST(
         (SELECT last_scanned_block FROM onchain_credit.chain_scan_cursors
           WHERE chain_id = 1 AND scope = 'portfolio:v2-campaign:arm-block'),
         (SELECT max(block_number) FROM onchain_credit.portfolio_flow_events_v2
           WHERE wallet IN (SELECT wallet FROM pt_wallets))
       ) AS to_block;

A bound that is too low is permanent, not transient, which is why it gets its own query. The re-derivation deletes and rewrites only block_number BETWEEN --from AND --to; rows above the bound are untouched, the derive cursor is a GREATEST upsert so nothing revisits them, and the next anchor for the holding is taken from the newest stored balance below the range. A row left above the bound therefore keeps its double-counted balance and hands it forward for good. On 2026-09-03 the arm block was 25,859,296 while this population's own highest row was 25,889,096, and one of the rows in between was a principal-token holding standing at 5,566,010.631614 — the double count exactly, to the wei. If the bound the query returns sits above the arm, let that block finalize before the build runs.

It has to be a re-derivation from the FLOOR, not a recent range. A holding's balance is carried forward from the balance the previous run stored, so a range that starts above the damage inherits the impossible starting point and adds correct movements on top of it. Worse here than merely wrong: the widened refusal now refuses any range that inherits a negative principal-token balance, so a narrow re-run reports a refusal rather than a repair.

bash
cd /opt/onchain-credit
set -a; . ./.env.local; set +a          # the builder is not a cron job: it needs the env here
# ranged, and scoped to the wallets query 1 returned; <to> is query 2's single value
npx tsx scripts/build-shadow-ledger.ts --from 24136053 --to <to> --wallet <wallet>
# ...once per wallet, then the reconciler

What to expect, judged as SHAPE first.

  • No refusal. A refused range names a holding, a balance and a transaction, and means the derivation still produces a negative principal-token balance: the repair did not land. Do not re-run scoped; report it.

  • No negative balance survives anywhere. Zero is the floor, whatever the count was before: SELECT count(*) FROM onchain_credit.portfolio_flow_events_v2 WHERE to_balance < 0;

  • The two sides of every collateral movement are now both recorded, and the check is an identity rather than a count. Every venue row whose asset is a principal token must have exactly one holder-side mirror, and every mirror must carry a pointer to the row it settles. Both columns come out of the same statement, so nobody has to remember a number:

    sql
    WITH pt AS (
      SELECT DISTINCT replace(position_key, 'pendle:pt:', '') AS token
        FROM onchain_credit.portfolio_flow_events_v2
       WHERE position_key LIKE 'pendle:pt:%'
    )
    SELECT wallet,
           count(*) FILTER (WHERE venue <> 'pendle')                              AS venue_side,
           count(*) FILTER (WHERE venue = 'pendle' AND kind LIKE 'transfer%')     AS holder_side,
           count(*) FILTER (WHERE venue = 'pendle' AND kind LIKE 'transfer%'
                              AND meta->>'settlementOf' IS NULL)                  AS unbound
      FROM onchain_credit.portfolio_flow_events_v2
     WHERE asset IN (SELECT token FROM pt)
     GROUP BY 1 ORDER BY 1;

    holder_side = venue_side on every row, and unbound = 0. (This identity holds for the venue family whose own event names the collateral token, which is every principal-token position the corpus has. A venue that names its own receipt token instead would add holder-side rows with no venue row of the same asset beside them, and the identity would then read as an excess on the holder side rather than a shortfall.)

  • The highest principal-token row is at or below --to, and its balance is the chain's. Take the newest pendle:pt: row, read PT.balanceOf(wallet) at its block, and expect the two to agree to the unit. That is the one check that says the bound was high enough.

  • 0x5d09098f…'s dollar chart lands at about plus $31,200, from the plus $417k the deploy left it at, and its charted-nowhere curve at about minus $90,500, which is where the guard had already put it. Its accrual line does not move at any point in this step. The two days that carried the phantom collapse: 2026-07-10 to 07-11 to about minus $2,529 and 2026-07-13 to 07-14 to about minus $5,057 — both negative, both small; a positive few thousand on either day means the repair did not land.

  • 0xaae6ae86… does not move, and not for the reason "it has no price". Its principal token IS priced (it is in the fixed-rate market registry, and its stored rows carry real marks). It does not move because its two acquisitions are unpriced market buys whose interval is withheld on both lines, and because the credit-back mirror and the redemption carry the identical mark and cancel exactly. The holding stops being overstated, which is the point of re-deriving it. Do not read "nothing moved" as "this wallet is inert": a future movement on it will move figures.

  • Reconciler: the withhold budget must be re-set from this run, not carried forward. The affected holdings lose their long unread stretches and gain per-movement unpriced-input withholds on the accrual line, which is the honest count for a fixed-rate holding, so the before-and-after numbers are not comparable and the new run is the baseline.

  • Comparator: the unattributed cells on 0x5d09098f… sit on its charted-nowhere curve and are the measure of the other open defect (its collateral is not valued at all). Expect that count to be broadly unchanged by this release and to fall only when that one lands. The dollar curve's own cells should stop carrying the two multi-million differences.

Do not run the two repairs in the other order. If the collateral-valuation fix lands first, its repair pass restates a collateral holding on a wallet whose own principal-token holding is still counted twice, and both numbers move again when this one runs. That repair is the step below.

GATED STEP: re-lay the wallets holding a Pendle PT as Morpho collateral ​

  • belongs to: the #754 Morpho PT collateral fix (v0.54.0)
  • executed: unverified

Prod held zero users after the full wipe of 2026-09-10 (docs/plans/pt-coverage-811-plan.md §0), so this step has had no population to act on since that date. That is not the same as having run: confirm against prod before deciding it is finished.

Runs once, on prod, after the release that carries the Morpho PT-collateral valuation fix (issue #754), and only there: staging reseeds from prod's dump nightly.

Run it AFTER the principal-token re-derive, never before. That section's closing paragraph is about this step by name: if the collateral-valuation repair lands first, it restates a collateral holding on a wallet whose own principal-token holding is still counted twice, and both numbers move again when the other one runs.

sql
-- read-only ordering check. Expect 0.
SELECT count(*) FROM onchain_credit.portfolio_flow_events_v2 WHERE to_balance < 0;

That check is a PROXY, and a one-directional one. Negative derived principal-token balances were the fingerprint of the defect #pt-wallet-leg-rederive repairs, so a non-zero result means that step has certainly not run and this one waits. A zero does not prove it ran: a wallet whose principal-token leg was double-counted without ever going negative passes it. The unambiguous signal is the settlement rows the #767 rungs write — a pendle:pt:… leg carrying transfer_in/transfer_out rows whose meta->>'settlementOf' names a morpho:market:…:collateral leg. Their absence on a wallet that has posted PT collateral means the re-derive is still owed.

Why history does not heal itself, and neither does the stored tip. The code fix makes every new FULL read carry the leg. The 6h tick does not do a full read for a quiet wallet: it RECOMPOSES from the wallet's stored legs, and a leg that has never been stored is never recomposed. A Morpho PT holder with no ledger movement is in no always-dirty set, so its snapshot tip stays collateral-less until something re-reads it. The replay below covers the tip and the history in one pass.

1. Scope it from the registries.

sql
-- read-only; use ITS output as the wallet list. The JOIN is the scope, NOT the `morpho-pt-%`
-- strategy_key prefix: on 2026-09-05 the join returns 73 markets and the prefix only 28, so
-- scoping by the name silently drops 45 markets' holders.
WITH pt_markets AS (
  SELECT lower(r.market_id) AS market_id
    FROM onchain_credit.morpho_market_registry r
    JOIN onchain_credit.pendle_markets p
      ON p.chain_id = r.chain_id AND lower(p.pt_address) = lower(r.collateral_address)
   WHERE r.chain_id = 1
)
SELECT DISTINCT wallet FROM (
  SELECT wallet, position_key FROM onchain_credit.portfolio_flow_events_v2
  UNION ALL
  SELECT wallet, position_key FROM onchain_credit.portfolio_position_snapshots
) x
 WHERE split_part(position_key, ':', 1) = 'morpho'
   AND split_part(position_key, ':', 3) IN (SELECT market_id FROM pt_markets)
 ORDER BY 1;

Take each wallet's before figures now, from the served endpoints, so the move across this step is measured rather than remembered:

bash
curl -s "https://creddit.xyz/api/portfolio/positions?wallet=<wallet>" \
  | jq '{outside: [.outside[] | {groupKey, reason}],
         usd: [.books[] | select(.book=="USD") | .rows[] | {positionKey, valueMarket}]}'

2. Re-lay each wallet's history. --fresh is the destructive full replay: it revokes the coverage anchor up front, replaces the wallet's snapshot history, and re-derives its v2 ledger whole-history in the same call. A gap patch is not enough — it would faithfully preserve the missing leg for every block below the anchor.

bash
cd /opt/onchain-credit
set -a; . ./.env.local; set +a          # not a cron job: it needs the env here
# once per wallet from query 1, serially
npx tsx scripts/backfill-portfolio-wallet.ts --uid <wallet> --fresh

--fresh lays tier 1 (a ninety-day window, span-bounded) and re-queues the wallet for the backward extension down to the history floor; the minutely drain completes that, so the script's exit is not the end of the repair. Wait for status='done' and a floor_ts at the floor:

sql
SELECT uid, status, floor_ts, covered_through_ts
  FROM onchain_credit.portfolio_backfill_state WHERE uid IN (<wallets>);

⚠ A position closed more than ninety days before the run is pruned from the replayed window until the queued deepening reaches it. That is --fresh's documented behaviour, not a fault of this repair, but it means the wallet's history is briefly shallower than it was.

3. Acceptance — identities the database produces, not counts written here.

  • Every READING that has the debt has the collateral. Per reading, not per wallet: a count-vs-count comparison over the whole history hides a reading missing its collateral whenever another reading carries a spare.

    sql
    WITH pt_markets AS (
      SELECT lower(r.market_id) AS market_id
        FROM onchain_credit.morpho_market_registry r
        JOIN onchain_credit.pendle_markets p
          ON p.chain_id = r.chain_id AND lower(p.pt_address) = lower(r.collateral_address)
       WHERE r.chain_id = 1
    )
    SELECT count(*) FROM (
      SELECT wallet, split_part(position_key,':',3) AS market, snapshot_ts,
             bool_or(position_key LIKE '%:debt')       AS has_debt,
             bool_or(position_key LIKE '%:collateral') AS has_collateral
        FROM onchain_credit.portfolio_position_snapshots
       WHERE venue='morpho-blue'
         AND split_part(position_key,':',3) IN (SELECT market_id FROM pt_markets)
       GROUP BY 1,2,3
    ) x WHERE has_debt AND NOT has_collateral;

    Expect 0, with one legitimate exception to check before calling it a failure. The reader emits a collateral leg only when the on-chain collateral is > 0, so a market left with bad debt after a FULL liquidation genuinely has debt readings and no collateral reading. Any row this returns should be matched against a seizure on that market at that block; what must not survive is a reading with live collateral on chain and no row for it.

  • A booked collateral leg carries a value, and the gate is ZERO.

    sql
    SELECT count(*) FROM onchain_credit.portfolio_position_snapshots
     WHERE venue='morpho-blue' AND position_key LIKE '%:collateral'
       AND book <> 'EXCLUDED' AND value_market IS NULL;

    Each such reading understates the published book value by the entire collateral — the group is structurally a carry whatever its values, so it is included and charted, and the leg with no mark contributes nothing while its borrow contributes in full. That is not "the odd isolated block": one reading is one wrong headline. If the count is not zero, enumerate the affected (wallet, snapshot_ts) and look at what the chart does at those points before accepting the run.

  • index_raw stays NULL on every Morpho collateral row (a non-zero count means something fabricated an index for a venue that has none).

    sql
    SELECT count(*) FROM onchain_credit.portfolio_position_snapshots
     WHERE venue='morpho-blue' AND position_key LIKE '%:collateral' AND index_raw IS NOT NULL;
  • The served response. The market leaves outside (it was {reason: "cross-book"}, "Debt without matched collateral") and the USD book carries two carry_trade rows, the collateral named by its PT ticker rather than by an address.

  • Expect the market-mark book value and the total-return line to RISE by the collateral being counted. HISTORICAL NOTE, superseded by #811 C: when this step was written a PT had no redemption mark at all, so the accrual line did not move and the redemption-mark book value went NEGATIVE on a levered wallet by the size of the borrow. A PT leg now carries a read-time accrual value (M34) and a financed group publishes both sides of a line or neither, so the accrual line moves WITH the market one and the redemption-mark book value is collateral − debt.

  • Reconciler: the withhold budget gains one W2 unpriced-input row per collateral reading on the accrual line, which is the honest count for a principal-token holding. Re-set the budget from this run rather than carrying the previous one forward; the two are not comparable.

No migration. No new table or column.

GATED STEP: the historical ledger build ​

  • belongs to: the rebuilt ledger's first build, per environment (v0.42.0 onward)
  • executed: unverified

Prod held zero users after the full wipe of 2026-09-10 (docs/plans/pt-coverage-811-plan.md §0), so this step has had no population to act on since that date. That is not the same as having run: confirm against prod before deciding it is finished.

Runs once per environment, after every stream's history is backfilled, and it is a gated step: it is long, it is per wallet, and its wall-clock is the number the rest of the campaign is planned from.

bash
cd /opt/onchain-credit && DATABASE_URL="$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)" \
  npx tsx scripts/build-shadow-ledger.ts

It writes flow rows and each wallet's derive cursor; it does not touch the position history, the backfill queue or the chart's building state. It is not a safe no-op for the product: the rows it writes are the served ledger, so a wallet it re-derives changes what that wallet's page shows. Mechanics, the two invocation modes and what complete means are in data-pipeline.

The build starts on 1 January 2026, and that is not the same number as the event store's depth. Two floors are in play through this whole campaign and confusing them is the easiest way to spend a night on the wrong thing:

blockwhat it means
raw ingestion floor22,527,558 (2025-05-21)how deep raw_events and its per-stream certificates go. Every stream sweep, every from_block, every rollout marker is written against this and none of it changes
derivation floor24,136,053 (2026-01-01)where the portfolio view's history begins. Every whole-history walk bottoms out here: the history build, the re-derivation trigger, the registration replay, the completeness certificate and the price-mirror preflight

The portfolio view supports everything from 1 January 2026 onward; positions held only before that are out of scope. Keeping the store deeper than the served window costs nothing (it is already ingested) and means widening the window later is a constant plus a rebuild, not a re-ingestion. It also removes a whole class of failure outright: the Fluid position resolvers went live at blocks 23,881,723 and 23,881,747, both a quarter of a million blocks below the derivation floor, so no supported range can ask a venue contract that does not yet exist.

Before starting:

  • Pause the minutely drain first, and leave it paused through the reconciliation. An un-paused drain sweeps the same wallets from the other end — harmless in itself, because the merge is idempotent and both writers serialise on the write lock, but it doubles archive reads and makes this step's wall-clock measurement worthless.
  • Read the entry check. It refuses if any tracked wallet already carries a derive cursor, which is the mechanical evidence that the pause held. There are exactly two legitimate non-zero causes and they are different: declare --re-entry when this step died and is being resumed, and --checkpoint-restored when a restored ledger checkpoint brought the cursors back. Record which in the run log. A restored checkpoint must be re-run with an explicit range (or its cursors cleared first), because a resume over restored cursors derives nothing and then passes every downstream check vacuously. The check binds this step — the sweep that measures the campaign. A run given an explicit range prints the count and proceeds, because every re-derivation targets a wallet that is already stamped past the range it is given; that is what the range is for.
  • --dry-run prints, per wallet, the cursor it found and the block it would start at, and writes nothing.

Afterwards, confirm every wallet is complete and that no [shadow-build/fail] line was printed. A wallet that derived rows and could not certify them is reported as a failure, not a success, and the run exits non-zero.

When a wallet refuses ​

A [shadow-build/fail] line means the run kept that wallet's rows rather than replacing them, and stopped walking it. Nothing is lost and nothing is wrong with the ledger; what is blocked is the claim that the wallet is derived, so every check that reads the completeness condition refuses until it clears. Do not re-run the sweep and hope. Read which refusal it is:

the line sayswhat happenednext step
refused its delete … terminal receipt … would be DELETEDthe run would have removed a receipt that closed a position without producing a replacement for the same position — because it did not cover that venue, or that venue's history is not certified over the whole rangecomplete the missing stream backfill for that venue, then re-run this wallet alone with an explicit range. If the venue's history is already certified, the derivation genuinely cannot restate that close and this is a defect, not an operational step
unresolvable-universe … declared venue(s) … but supplied no series universethe derivation could not say which legs it was able to resolve on a venue it claims to have covereda defect in the derivation, not an operator step. Do not clear it by narrowing the venue list
unresolvable-universe … NOT a superset of the leg(s) its stored rows already namea vault or market the wallet's stored rows name has left the registry, so the run cannot re-derive itre-list that vault or market in the registry and re-run the wallet with an explicit range. If it is genuinely gone, see the box below — this one does not clear itself
adapter-error … at least one transaction in this range produced no rowsone transaction's decode threw, so that range was read incompletely. The delete and the stamp are both withheld rather than treating the unread rows as phantomsfix the decode (it names the transaction) and re-run the wallet with an explicit range
rows written, cursor NOT stamped — uncovered: …the rows are in, the claim is withheld until the named streams certify back to the derivation floor (24,136,053). A stream certified from the deeper raw floor already satisfies itwait for that backfill. For a wallet registered minutes ago this is the ordinary state and it clears itself

Two of these can never clear by waiting, and the runbook must not send an operator to wait for them

A de-registered venue and native ETH a wallet has since spent to zero cannot re-enter a replay universe: the sentinel enters only from a live non-zero balance, and a delisted vault is not in the registry to be found. The refusal is still correct — the run genuinely cannot re-derive those rows — but "re-run after the backfill" is telling that operator to wait for something that cannot arrive.

A refused range also stops that wallet's walk, by design — a later range must not commit above a hole and certify across it — so the wallet stays short of the arm block and uncertified for as long as the refusal stands. There are exactly two ways out and both are decisions, Fred's rather than the operator's:

  1. Re-list the venue in the registry. The run can resolve it again, the refusal clears on the next re-derivation, and nothing was lost.
  2. Decide the rows may go, and remove them deliberately. That is precisely what the merge refused to do on its own, and no tool here will do it for you: it is a recorded act, naming the wallet, the venue, the block range and the reason in the campaign's run log, after which the re-derivation has nothing left to protect and proceeds normally.

Never widen the delete to clear a refusal. The refusal is the only thing standing between a close the run cannot restate and a position that never ends.

Re-deriving one wallet later — after a stream is enabled post-build, or to repair a single wallet — takes an explicit range and derives that whole range, cursor or no cursor:

bash
npx tsx scripts/build-shadow-ledger.ts --wallet 0x… --from 24136053 --to <recorded arm block>

Passing --from is what selects that behaviour. Omitting it resumes from the wallet's cursor, which for an already-certified wallet derives nothing and exits clean — a repair that never happened, reported as one.

--from below 24136053 is refused, and the old command is the reachable way in

Releases up to v0.46.0 printed this command with --from 22527558 — the raw ingestion floor, which is where the event store starts, not where the portfolio view does. That number is still in operator scrollback and in every published copy of this page from those releases, so running it against current code is the likely mistake, not a hypothetical one.

The run now refuses it and exits 2 before deriving anything. It is not silently raised to the derivation floor: the ranged mode exists precisely so an operator's explicit range is never shortened behind their back, so a range that cannot be honoured is rejected out loud instead. Re-run with --from 24136053.

Obeying it would have been worse than the wasted hours: the run derives roughly 1.6M blocks below the supported window, marks the wallet as covering its whole history, stamps its cursor and exits 0 — leaving that one wallet's history deeper than every other wallet's, decided by which command someone happened to paste.

GATED STEP: reset the two Pool streams' coverage certificates ​

  • belongs to: the widened Aave/Spark Pool event set (v0.54.0)
  • executed: unverified

Prod held zero users after the full wipe of 2026-09-10 (docs/plans/pt-coverage-811-plan.md §0), so this step has had no population to act on since that date. That is not the same as having run: confirm against prod before deciding it is finished.

aave-pool and spark-pool used to request two events (LiquidationCall, UserEModeSet). They now request eight — Supply, Withdraw, Borrow, Repay and the two Deficit events joined them. Their event_coverage rows did not change, because a coverage row certifies a stream NAME over a block range and knows nothing about the event set that was being requested. Measured read-only on prod, both rows read ('*', 22527558, live) while six of the eight topics have no row anywhere:

sql
SELECT stream, topic0, count(*), min(block_number)
  FROM onchain_credit.raw_events
 WHERE stream IN ('aave-pool','spark-pool') GROUP BY 1,2;
-- two topic0s per stream, from 22,527,761 up. The other six: nothing.

So the rows are a completeness claim over an index that holds a quarter of what the claim now covers — see the rule in the schema doc.

Do not run this at the release deploy. Today the only served read of these two streams binds a single scalar topic0 = LiquidationCall, which IS indexed to the floor, so the certificate is still true for everything that reads it. Withdrawing it early would take every wallet holding an Aave or SparkLend position off the ledger path and onto the chain fallback (the JIT gate and the historical backfill gate both require these two rows to reach back to their read's start block) for no gain at all.

Run it as the FIRST step of the backfill that re-earns them, and before any verification step that counts coverage rows — a stale row is exactly what makes such a check pass vacuously:

bash
# PROD. Immediately before backfilling the two Pool streams over the widened event set.
sudo -u postgres psql -d creddit -c \
  "DELETE FROM onchain_credit.event_coverage WHERE chain_id = 1 AND stream IN ('aave-pool','spark-pool') AND address = '*';"

Expect the always-on ingester to re-insert both rows within a cycle at its current tip; that is correct, and the backfill is what walks from_block back down to 22,527,558. Do not try UPDATE … SET status = 'backfilling' instead: the live scan re-stamps live every cycle and from_block merges with LEAST, so the update is inert.

GATED STEP: reset the two Fluid streams' coverage certificates ​

  • belongs to: the widened Fluid event set (v0.54.0)
  • executed: unverified

Prod held zero users after the full wipe of 2026-09-10 (docs/plans/pt-coverage-811-plan.md §0), so this step has had no population to act on since that date. That is not the same as having run: confirm against prod before deciding it is finished.

Same rule, same shape, two more streams, and one of them fixes a class of loss that is currently invisible.

fluid-operate used to request two vault events. It now requests three: the event a Fluid vault emits when it writes a position off entirely joined them. That event is the ONLY trace such a write-off leaves — the vault returns before emitting its ordinary liquidation event — so a pipeline that never requested it cannot see an absorbed position at all, and 13 of Fluid's 179 live vaults carry absorbed bad debt today. fluid-nft used to request the position transfer alone and now also requests the factory's mint signal, which is what lets a position opened inside a replay window anchor without an archive read.

Do not run this at the release deploy, for exactly the reason above: today's served read of fluid-operate binds the two original topics, which ARE indexed to the floor, so the certificate is still true for everything that reads it. Withdrawing it early puts every Fluid wallet on the chain fallback for no gain.

Run it as the FIRST step of the backfill that re-earns them, and before any verification step that counts coverage rows:

bash
# PROD. Immediately before backfilling the two Fluid streams over the widened event set.
sudo -u postgres psql -d creddit -c \
  "DELETE FROM onchain_credit.event_coverage WHERE chain_id = 1 AND stream IN ('fluid-operate','fluid-nft') AND address = '*';"

The same DELETE-not-UPDATE caveat applies, and for the same reason.

erc4626 widened too, and owes NOTHING — checked, not assumed. It gained Morpho Vaults V2's forced-deallocation event, without which a forced-deallocation penalty is indistinguishable from a queued exit and opens a position waiting on a payout that can never arrive. It is exempt because the stream has never been scanned: on 2026-08-21, read-only on both prod and staging, it held zero event_coverage rows and zero raw_events rows. There is no range below the change to invalidate, so there is no delete to run and none should be scheduled — its one-time backfill earns the certificate over the full event set from the start. Re-run the check below before trusting this paragraph; once that backfill has run, a further widening owes the reset in full, on 546 addresses over 3.2M blocks.

sql
-- Both must be 0 for the exemption to hold.
SELECT (SELECT count(*) FROM onchain_credit.event_coverage WHERE stream = 'erc4626') AS coverage_rows,
       (SELECT count(*) FROM onchain_credit.raw_events     WHERE stream = 'erc4626') AS stored_logs;

GATED STEP: re-derive the holder whose redemptions shared a transaction with a forced pull ​

  • belongs to: the #889 Vaults V2 forced-pull redemption fix — v0.64.0
  • executed: 2026-09-17

Run 2026-09-17 (v0.64.0): nothing to re-derive. The same release carried the coverage-rule account wipe, run at 13:22Z, which deleted the one affected holder along with every other account; step 1's scope query returns no row, so per step 1 this is recorded rather than run. The holder was tracked until the wipe (floor 25,742,367, derive cursor 25,991,218). Any history the wallet gets from here is derived by the fixed code.

Runs once, on prod, after the release that carries the fix, and only there. Staging cannot even be a rehearsal: its nightly reseed restores prod's dump and then scrubs it, and the scrub truncates the whole user-data graph — accounts, tracked wallets and the flow ledger alike — so staging holds no wallet for this to act on and never will.

#889 ships in two halves and this step serves both. The first restores the redemptions the transaction-keyed rule deleted; the second books the forced-pull fee itself as a row. The run is the same command either way and it is idempotent over the range, so running it after the first half and again after the second is harmless — it simply re-derives, and the second pass adds the five fee rows. If both halves ship in one release, one run does everything.

Why the release is not enough on its own. The fix changes what the derivation does with a transaction that carries a forced liquidity pull and the holder's own withdrawal — the shape Morpho's app builds whenever an exit needs more than the fund's idle cash. It is forward-looking only. Nothing re-derives below a wallet's derive cursor: the 6h tick and the JIT persist both resume at cursor + 1, so every redemption already dropped stays dropped, and the position keeps publishing the loss. One tracked holder is affected and no other wallet has ever had a forced pull naming it.

1. Scope it from the ledger, not from this page. The wallet may have been unlinked, and its floor and cursor are both read at the moment you run, never copied from here.

sql
-- read-only. Expect ONE row. An empty result means the holder is no longer tracked and this
-- step has nothing to act on; record that rather than hunting for the wallet.
SELECT aw.wallet,
       a.history_floor_block                    AS from_block,
       c.last_scanned_block                     AS to_block
  FROM onchain_credit.account_wallets aw
  JOIN onchain_credit.accounts a  ON a.uid = aw.account_uid
  LEFT JOIN onchain_credit.chain_scan_cursors c
         ON c.chain_id = 1
        AND c.scope = 'portfolio:derive:v2:1:' || aw.wallet
 WHERE aw.wallet = '0x68e7e72938db36a5cbbca7b52c71dbbaadfb8264';

The issue recorded a floor of 25771074 for this wallet on 2026-09-16; read both values again rather than reusing that one. --from must be the wallet's own floor, not the global derivation floor and not a recent block: the run certifies what it derives only when its bottom is at or below the wallet's floor or exactly at cursor + 1, and a range that starts above the damage inherits the balance the damaged rows left behind.

If from_block comes back NULL, the account has no floor pair stored — a boundary block that never resolved, or a row written before migration 104's grandfather. That is an ordinary state, not a fault, and the engine already has an answer for it: UNRESOLVED_HISTORY_FLOOR, which is the derivation floor 24136053. Pass that as --from. It is below everything this wallet has, so it certifies and costs only walk time. A NULL to_block is different: it says the wallet has never been derived on this chain, which for this holder cannot be true — stop and report it rather than substituting the chain tip.

2. Take the "before" figures first, because the repair restates them and there is then nothing to compare against.

sql
-- read-only. The leg's stored history, and what it currently says the holder holds.
SELECT count(*)                                   AS rows_stored,
       count(*) FILTER (WHERE kind = 'withdraw')  AS withdrawals,
       max(block_number)                          AS highest_row,
       (SELECT to_balance FROM onchain_credit.portfolio_flow_events_v2
         WHERE chain_id = 1 AND wallet = '0x68e7e72938db36a5cbbca7b52c71dbbaadfb8264'
           AND position_key = 'vault:0x093272c07700d3ca5301c3bf9b3a392624179e2f'
         ORDER BY block_number DESC, log_index DESC LIMIT 1) AS last_to_balance
  FROM onchain_credit.portfolio_flow_events_v2
 WHERE chain_id = 1 AND wallet = '0x68e7e72938db36a5cbbca7b52c71dbbaadfb8264'
   AND position_key = 'vault:0x093272c07700d3ca5301c3bf9b3a392624179e2f';

3. Re-derive, RANGED and scoped to the one wallet. Ranged because a bare sweep resumes at the cursor and derives nothing, which is the silent no-op this mode exists to prevent; scoped because exactly one wallet is affected and re-deriving the rest would be a multi-hour campaign for no change.

bash
cd /opt/onchain-credit
set -a; . ./.env.local; set +a          # the builder is not a cron job: it needs the env here
npx tsx scripts/build-shadow-ledger.ts \
  --wallet 0x68e7e72938db36a5cbbca7b52c71dbbaadfb8264 \
  --from <query 1's from_block> --to <query 1's to_block> --range 50000

--range 50000, not the 200,000-block default the builder falls back to. The prod role carries statement_timeout = 30s, and a 200,000-block range's reads do not finish inside it: the run is cancelled mid-range and writes nothing (measured 2026-09-05). This is the only step on this page that passes --range — take the width from here, not from a precedent.

4. Then the acceptance reconciler, read-only, on the same wallet.

bash
cd /opt/onchain-credit && DATABASE_URL="$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)" \
  npx tsx scripts/ops/reconcile-ledger.ts --wallet 0x68e7e72938db36a5cbbca7b52c71dbbaadfb8264

What moves, judged as SHAPE first.

  • Withdrawal rows APPEAR; nothing that should survive is deleted. Fourteen were missing inside the wallet's stored history window on 2026-09-16 — 15,363,939.48 USDC and 14,542,419.87 shares between 2026-08-18 and 2026-09-16, the two largest being 5,611,414.579986 USDC on 09-07 and 5,328,792.398150 USDC on 08-30. Re-run query 2: withdrawals rises by the number the range actually held, and rows_stored rises by the same amount — plus the five fee rows below, which are withdraw rows too. No deposit moves: none of this wallet's deposits shares a transaction with a forced pull, so a changed deposit count means the range or the scope is wrong.

  • The leg's last stored balance is the chain's — and AFTER the run that is a verdict, not a hope. Re-run query 2 for highest_row and last_to_balance, read IVaultV2(0x093272c0…).balanceOf(0x68e7e729…) at that block, and the two must agree to the unit. The same pass that inserts the rows recomputes every to_balance from a fresh archive anchor, so agreement is what a landed run produces. A disagreement is a STOP: do not run the reconciler (step 4) and do not re-run the builder; capture both figures, the block they were read at, and the run's [shadow-build] lines, and escalate. The run wrote rows whose balances are not the chain's, and a second pass over the same range would only write them again.

  • Whether the BEFORE figure moves is a separate question, and it is measured rather than predicted. Take the same reading before the run too: the issue recorded a stored 9,763,396,524,832,301,595,415,391 against about 826,737.79 shares on chain on 2026-09-16, but an offline replay of the same logs closed on the chain's figure with the old code as well, so how far the stored number moves depends on how the stored series was built. Nothing about the step is judged on that; the acceptance is the bullet above, plus the row count and the withdrawal amounts.

  • The position CLOSES mid-history and REOPENS, twice, and that is the chain. Two of the restored redemptions are FULL exits rather than partial ones — block 25,864,842 (2026-08-30 01:37:23Z) and block 25,923,774 (2026-09-07 06:45:59Z) — and after each one the holder deposits again. Every time quoted here is the BLOCK's own timestamp, like the fee table below; the feed prints the stamp stored with the event, which is interpolated on historically swept rows and can sit a minute or more off the block's (issue #749), so identify a row by its block and not by its clock. Worked through on the second exit, which is the one the issue is about: balanceOf(0x68e7e729…) is 5,307,605,297,946,978,707,439,278 at block 25,923,773, exactly the shares that withdrawal burns, and 0 at 25,923,774; the next deposit lands at block 25,925,046 (2026-09-07 11:01:11Z, 254,252.686546 USDC for 240,478.632551637336367068 shares, tx 0xec922516… log 231) and opens a SECOND series on the same leg. So the repair writes a terminal row in the middle of the wallet's stored history and the position reads closed-then-reopened on that date, on the Activity feed and in the history chart alike. Expect it: restoring the row that ENDED the position is the point of the repair, and a close followed by a reopen mid-history is otherwise a shape worth being suspicious of. (Reading further out, balanceOf is 826,737,792,636,922,870,855,503 at 25,989,485 — the holder is still in.)

  • The position's "Yield earned" stops carrying the redemptions. It read about −$15.36M before; afterwards it is the small figure the position actually earned. The USD book's total-return and accrual lines restate on the next page load — they are read-path, so no second step is owed for them.

  • The five forced-pull FEES appear too, as withdrawals of nothing. The release that carries the second half of #889 books the fee itself as a row — amount_raw = 0, because none of it reached the holder, and qty_delta = −shares, because the shares were burned — so the run inserts these five as well as the fourteen redemptions. Verified log for log on chain 2026-09-17, each fee's Withdraw immediately followed by its ForceDeallocate:

    blockUTClogamount_rawqty_delta (shares)fee
    25,946,5862026-09-10 11:07:474780−30248612097147649383.199930 USDC
    25,953,0432026-09-11 08:44:115710−47162015625608425854.989951 USDC
    25,965,4682026-09-13 02:17:595950−14172970297497541371.499986 USDC
    25,974,4862026-09-14 08:25:5915490−4635837957286525130.490738 USDC
    25,988,0382026-09-16 05:46:596050−29846238961673792013.160410 USDC

    That is 12.606567493921393374 shares and $13.341015 in total. Each row carries meta.penalty = true and the fee on meta.penaltyAssets, so they are separable from the fourteen redemptions in one query; none of them adds to any flow figure, because their amount is zero.

  • Expected anomalies: NONE. Under the first half of #889 alone each of the five fees was a quantity-drift note saying the leg lost quantity with NO ROW to carry it — the designed report at that point. With the fee booked as a row there is nothing left to report: the leg's own rows add up to the balance stored on them. A drift note on this leg after the run, or a withdrawal still missing, is a stop.

  • No other wallet moves. Nothing else has ever had a forced pull naming it, so a second wallet's figures changing means the run was not scoped.

Cautions. Never point backfill-portfolio-wallet.ts --fresh at this: it is a different tool, and a refused delete there parks the wallet and needs a hand restore. The builder's own refusal is loud and harmless by comparison — it withholds the stamp and exits non-zero, which means the run did not certify and must be reported rather than re-run narrower. And do not run this on staging: the nightly reseed takes it back.

The coverage rule: wipe every account (no history rebuild) ​

  • belongs to: migration 105 / the coverage rule — v0.64.0
  • executed: 2026-09-17

Run 2026-09-17 (v0.64.0), 13:22Z, after 105–108: 11 accounts, 5 tracked wallets, 1,728 snapshot rows, 241 flow rows, 11 wallet-token coverage rows and 1 held-PT row deleted; the '*' marker kept; SESSION_SECRET rotated; app and ingester restarted. The backup in step 1 misses the partitions: -t on a partitioned table dumps the parent only, which holds no rows. The run used --table-and-children (pg_dump 16) for every table the wipe touches. --execute also needs --confirm-db=creddit, which the command above omits; without it the script refuses. And the ingester alarm's feed-lag arm starts paging about 6h later while no wallet is enrolled: with an empty list the wallet-token stream is not emitted, so its cursor stops while its rollout marker stays (see the ingester alarm). The first sign-in clears it.

Run 2026-10-03 16:21Z (Fred: wipe before step 2): 13 accounts, 11 tracked wallets, every reading, ledger row and job deleted via reset-portfolio-users.ts --execute after a dry run; backup /root/backup-users-20261003T162118Z.sql (data-only, --table-and-children, 29 COPY blocks); SESSION_SECRET rotated (env backup /root/.env.local.bak-20261003T162118Z); app and ingester restarted; 26 wallet-token/native-eth coverage rows and 5 held-PT rows deleted, 0 orphan jobs; worker restarted; enrolled wallets: 0; pages 200.

The standing procedure is now deleting portfolio users in the runbook: this recipe, plus (from the ledger-first release on) the ledger worker's stop before the wipe and the derivation queue's jobs of the deleted wallets cleared after the ingester's restart. The commands below are this entry's own, as written for 2026-09-17 (the note above says where that run differed from them).

Fred's decision: every wallet is deleted and NO history is rebuilt. The sweep universe changes with this release — eleven bare tokens start being read, eighteen assets are added, eleven are retired — so every stored history is a history of a different universe from the one the release reads. Re-deriving would take hours and produce a history nobody asked for; deleting is instant and the next six-hourly tick starts a clean one.

Run it between 6h ticks (the refresher runs at 50 */6 UTC), as the postgres user, and take a data-only backup first.

bash
# PROD. 1. back up what is about to be deleted.
sudo -u postgres pg_dump -d creddit --data-only \
  -t onchain_credit.accounts -t onchain_credit.account_wallets \
  -t onchain_credit.portfolio_position_snapshots -t onchain_credit.portfolio_flow_events_v2 \
  > /root/backup-users-$(date +%F).sql

# 2. the wipe itself, as the postgres user (the script writes through the socket).
sudo -u postgres bash -lc 'cd /opt/onchain-credit && \
  DATABASE_URL="postgres://postgres@/creddit?host=/var/run/postgresql" \
  npx tsx scripts/ops/reset-portfolio-users.ts --execute'

# 3. rotate the session secret, so no old cookie resolves to a deleted account,
#    and restart both processes so they pick it up AND drop the enrolled-wallet
#    list they are still holding.
#    (edit SESSION_SECRET in /opt/onchain-credit/.env.local first)
pm2 restart onchain-credit --update-env
pm2 restart creddit-event-ingester --update-env

# 4. the two tables the reset script does not own. AFTER the restart, or the
#    still-running ingester re-writes the coverage rows underneath the DELETE.
sudo -u postgres psql -d creddit -c \
  "DELETE FROM onchain_credit.event_coverage WHERE stream = 'wallet-token' AND address <> '*';"
sudo -u postgres psql -d creddit -c "DELETE FROM onchain_credit.portfolio_held_pts;"

# 5. confirm the ingester enrolled nothing. Wait one 60s cycle after step 4: the line prints
#    only when the count CHANGES, so the pass is the drop -- `enrolled wallets: 11 -> 0`.
sleep 70
pm2 logs creddit-event-ingester --lines 50 --nostream | grep 'enrolled wallets'

Restart before the deletions, not after. A running ingester keeps writing the wallet-token coverage rows step 4 deletes — its in-flight enrolment backfill re-stamps them as it works. Run 2026-09-23 with the old ordering and three of the eleven rows came back seconds after the DELETE; the restart then re-read the enrolment list, found those rows and resumed backfilling three deleted wallets (enrolled wallets: 3), so the deletion had to be repeated. The restart is what stops that backfill; it does not drop a list. The ingester re-reads its enrolled wallets every cycle, and the read unions the wallet-token coverage rows themselves, so between steps 3 and 4 it enrols the eleven wallets from those rows alone with every account already deleted — which is why step 5 is read AFTER step 4, one cycle later.

The wallet-token coverage rows go because the stream's universe widened: a certificate earned over the old token set is not true of the new one, and DELETE rather than UPDATE is what makes the next enrolment re-earn it. portfolio_held_pts goes because it is a per-wallet index of a set that no longer has any wallets in it.

GATED STEP: give the running ingester a 120s kill timeout ​

  • belongs to: the ingester feed-lag alarm + kill-safe reorg repair release (issues #860 / #858) — v0.64.0
  • executed: 2026-09-17

Run 2026-09-17 (v0.64.0): read (unset -> pm2 default 1600) before, 120000 after the first form (pm2 restart … --kill-timeout 120000 --update-env + pm2 save), so the box's pm2 merges the flag on restart. The next hand-run of the alarm printed no grace line.

docs/deployment.md now starts the ingester with --kill-timeout 120000, so a restart lets the current cycle finish instead of SIGKILLing it after pm2's default 1.6 seconds. That is a change to the documented start command only. scripts/ops/restart-ingester.sh — which is what every prod deploy runs — issues pm2 restart, and a restart reuses the stored process definition, so the ingester already running on prod keeps whatever kill_timeout it was created with until somebody changes it here.

Run it once, on prod, at any quiet moment (it restarts the ingester, which every deploy does anyway). Read the value back before and after. Current pm2 does merge a restart's own CLI options into the stored process (God.restartProcessId → Utility.extendExtraConfig copies the invocation's config over pm2_env), so the first form should suffice — but the version installed on the box is what decides, and the read is what settles it.

bash
# PROD. 1. what the running process has today (prints ONE number, never the process list --
#           `pm2 jlist` carries every process's environment, `.env.local` secrets included).
pm2 jlist | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{
  const p=JSON.parse(s).find(x=>x.name==="creddit-event-ingester");
  console.log(p?.pm2_env?.kill_timeout ?? "(unset -> pm2 default 1600)")})'

# 2. set it, and persist the definition so a reboot keeps it.
pm2 restart creddit-event-ingester --kill-timeout 120000 --update-env
pm2 save

# 3. read it back. Expect 120000.
pm2 jlist | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{
  const p=JSON.parse(s).find(x=>x.name==="creddit-event-ingester");
  console.log(p?.pm2_env?.kill_timeout)})'

If step 3 does not print 120000, this pm2 does not merge the flag on restart. Re-create the process from the runbook's start command instead — the ingester is down for the seconds between, which is the same gap every deploy's restart opens:

bash
# PROD, only if the read above disagreed.
cd /opt/onchain-credit
pm2 delete creddit-event-ingester
pm2 start scripts/ingester/run-ingester.sh --name creddit-event-ingester --time --kill-timeout 120000
pm2 save
pm2 logs creddit-event-ingester --lines 30      # expect a `[ingester] starting` line

From here the hourly alarm confirms it for you. check-ingester-freshness.ts reads kill_timeout back on every tick and prints a non-paging note while it is not 120,000 ms, so the step is settled by reading the log rather than by another SSH round trip — and a later pm2 resurrect from a stale dump that drops the field announces itself the same way.

Read the NEWEST TICK, not the whole file. The log is append-only and never rotated, so every grace note written between this release's deploy and this step stays in it for ever: grepping for the note alone always finds those and reads as a failure on a step that succeeded. Anchor on this checkout's label instead — prod and staging share the file, which is keyed by script — and look at the last tick's two or three lines for the ABSENCE of a grace note among them.

bash
grep 'env=onchain-credit$' /tmp/onchain-credit-cron/onchain-credit-check-ingester-freshness.log | tail -3
# after the next tick: a freshness `ok:` line and a feed-lag line, and NO `grace period` line
# beside them. A grace line among the newest names the value the box actually has.

Verification that it did what it is for, next time the ingester is restarted: the log ends with [ingester] SIGTERM received; finishing the current cycle then exiting followed by [ingester] stopped. Under the 1.6s default the second line is missing, because the process never reached it. Read the last lines rather than counting matches — a count over the retained window includes every earlier graceful stop and so proves nothing about this restart.

bash
pm2 logs creddit-event-ingester --lines 5 --nostream

GATED STEP: rebuild the wallets whose window was cut at their first move ​

  • belongs to: the held-at-floor window fix (issue #852, branch fix/held-at-floor-window) — the next release
  • executed: 2026-09-22

Recorded 2026-09-22, not run: there is nothing left to rebuild. The nine wallets this step was written for were all test wallets, and Fred had them deleted on 2026-09-22 14:14Z, before the release: accounts, tracked-wallet rows, spine, flow ledger, wallet index, backfill state, their wallet-token coverage rows and their portfolio:derive:v2: cursors, in one transaction (data-only dump first, /root/backup-users-20260922.sql; SESSION_SECRET rotated and the app and ingester restarted, per the reset recipe). Step 1's scope query returned no row afterwards, so per its own rule this is recorded rather than run. Every wallet registered from the release on is built by the fixed code; a wallet that shows the defect again is a NEW instance and takes this step as written.

That delete was a hand recipe, and it is now written down, corrected, as a standing procedure: deleting portfolio users. Its cursor selector matched the scope's last 42 characters, which catches a wallet's bare derive cursor and misses its suffixed records (:jit-pending, :replay-deferred); the runbook's selects by the scope's own wallet part, and adds the ledger worker's stop and the derivation queue. Any suffixed record that run left was deleted by the full wipe of 2026-09-23 (the reset tool deletes the whole portfolio:derive:v2:% prefix), so nothing of it remains on prod.

Runs once, on prod, after the release that carries the fix, and only there. Staging is not a rehearsal: its nightly reseed restores prod's dump and then scrubs the whole user-data graph, so it holds no wallet for this to act on.

Why the release is not enough on its own. The fix changes where a REPLAY opens, and a replay runs once, when the wallet is registered. Nothing re-opens a window afterwards: the 6h tick and the JIT persist both append above the wallet's tip, and a re-add takes the gap-patch path, which by design never touches anything at or below the coverage anchor. So every wallet already built under the unconditional raise keeps the cut chart it was given — the fix only spares the wallets registered from here on. Putting the dropped days back means re-running the build for each affected wallet, which is what this step is.

What was wrong, in one line. The replay opened at the wallet's stored floor RAISED to its first curve-starting activity, always. That raise exists for a wallet that held nothing at its floor, whose chart would otherwise open on a flat-zero lead-in. Applied to a wallet that already held a position there, it dropped every day before that wallet's first in-window move — 25 days on 0xea88d13e…7974, which held a Pendle PT and an sGHO balance right through its floor — and where the first move was the EXIT of one of those positions, it opened the chart on the day the wallet closed something.

1. Scope it from the database, not from this page. Read-only, on prod. The wallets to rebuild are the ones whose chart start sits ABOVE their stored floor; the set moves with every signup, so take it at the moment you run.

sql
-- read-only. One row per wallet whose window was cut, deepest cut first.
SELECT a.uid,
       a.history_floor_ts,
       b.floor_ts                                          AS chart_start,
       (b.floor_ts::date - a.history_floor_ts::date)        AS days_cut
  FROM onchain_credit.accounts a
  JOIN onchain_credit.portfolio_backfill_state b USING (uid)
 WHERE b.status = 'done'
   AND b.floor_ts > a.history_floor_ts
 ORDER BY days_cut DESC, a.uid;

On 2026-09-22 this listed nine wallets, and eight of the nine are the defect. The ninth, 0xef08c6a4…07c5, held idle USDC and ETH at its chart start and nothing else, which is the shape the raise exists for, so it is expected to keep its 2026-09-16 start and to still appear in this query after the rebuild. Treat that as an expectation and not as a check: what decides the window is what the wallet held at its floor (2026-08-18), a month below the day that observation was made, and only the rebuild's own floor read answers that. If its start moves down, the wallet held something curve-starting at its floor after all and it was a ninth instance of the defect, not a regression. Record the rows as they come back rather than assuming that list — wallets added since will be in it, and a wallet may have been unlinked.

2. Take the "before" figures, per wallet, because the rebuild restates them — and because the second query is what a refusal is undone from (below).

sql
-- read-only. Substitute the uid. The chart's first day and how much history it holds.
SELECT min(snapshot_ts) AS first_point,
       max(snapshot_ts) AS last_point,
       count(*)         AS rows_stored
  FROM onchain_credit.portfolio_position_snapshots
 WHERE wallet = '<uid>';
sql
-- read-only, and KEEP THIS OUTPUT. These four values are the wallet's whole build state;
-- a refused run revokes the anchor, and this is the only record of what it was.
SELECT status, floor_ts, covered_through_ts, covered_through_block
  FROM onchain_credit.portfolio_backfill_state
 WHERE uid = '<uid>';

3. Rebuild, one wallet at a time. The history writers serialise on one advisory lock, so running these in parallel only queues them behind each other; the drain keeps running throughout, since it claims queued rows and these are done.

bash
# PROD. Per uid from step 1, one at a time.
cd /opt/onchain-credit
scripts/run-cron.sh backfill-portfolio-wallet.ts --uid <uid> --fresh

Output lands in /tmp/onchain-credit-cron/onchain-credit-backfill-portfolio-wallet.log. The file is prod's own — the log name carries the checkout — but it is still append-only across every run of this job, so anchor on the run you just started. The line to read is the probe's: held at floor: yes (N curve-starting leg(s) @block B) for a wallet this step is meant to fix, followed by a replay whose grid opens at the wallet's stored floor.

--fresh is DESTRUCTIVE by design, and it is the only mode that can do this: it replaces the wallet's whole history, which is the point — the cut chart has to go. Two consequences an operator must know before running it.

  • The wallet's 6h resolution is thinned to daily, over its WHOLE history, permanently. The replay deletes every snapshot at or below its own last grid point — the 6h seam at ~now, not the signup date — and re-lays daily UTC midnights plus that one seam. So the 6h live points written since the wallet was added are not merely joined by a daily pre-signup span: they are replaced by it. The wallet's chart reaches weeks further back and draws one point per day where it drew four, and the 6h cadence only resumes from the next tick after the rebuild. This is the consequence to weigh before running a destructive command against a live user's portfolio, and it applies to every wallet in step 1, not only to the ones the fix moves.
  • A position that has dropped out of the window since the original build is pruned, because a fresh run re-derives the replayed set at run time.

Both are the documented behaviour of a fresh replay, not side effects of this step. The run re-earns the coverage anchor when it completes.

If a rebuild REFUSES, stop. A --fresh run revokes the wallet's coverage anchor BEFORE its first destructive write, deliberately, so that a run dying mid-wipe cannot leave its retry dispatched to the gap path. The §4.8 universe-superset refusal is taken after that revoke and before the wipe, so a refused run writes and deletes nothing and still ends with the anchor gone. That combination is terminal: the drain claims queued rows only, so it never retries an error row of its own accord, and re-adding the wallet re-queues it onto the fresh path where the same refusal fires again. This is not hypothetical — it happened on prod on this exact command during the Morpho PT relay step (#807), on a wallet whose stored rows named assets it had since disposed of, and the recovery was a hand restore of the row.

  • What it looks like. The CLI exits non-zero and run-cron.sh raises the ordinary cron alert (a [fail] line and a non-zero exit are both halves the alert needs). In the log: [fail] backfill <uid>: flow wipe at/below <block> REFUSED: N stored wallet asset(s) missing from the replay universe (…), then [backfill <uid>] REFUSED before the first destructive write: status 'error', no coverage anchor, nothing written.
  • What it leaves. status='error' with the verdict on the row, floor_ts untouched, the wallet's OLD history and flow rows fully intact, and covered_through_ts / covered_through_block NULL. The user's chart is unchanged, still cut; nothing is lost.
  • Restore it by hand, from the four values step 2 recorded for that wallet. Nothing else will: UPDATE onchain_credit.portfolio_backfill_state SET status = 'done', error = NULL, covered_through_ts = '<recorded>', covered_through_block = <recorded> WHERE uid = '<uid>'; That puts the wallet back exactly where it was before the run, cut chart and all, and its 6h ticks resume on the gap path.
  • Then stop and decide, do not run the other seven. The refusal says the replay universe no longer covers assets the wallet's stored rows name, which is a property of that wallet's holdings and not of this fix; whether the remaining wallets share it is a question to answer before spending another destructive run. The verdict line's own remedy says which case it is: an ERC-20 miss clears once the wallet-token backfill covers the wallet, and a native-ETH miss cannot clear at all while the live balance reads zero.

4. Re-run step 1. A wallet that held a curve-starting position at its floor now reports floor_ts = history_floor_ts and has dropped out of the result. 0xef08c6a4…07c5 is expected to remain, for the reason step 1 gives — but its floor read is what decides that, so a start that moves down on that wallet is a ninth instance of the defect and not a regression. Record before/after per wallet under this step's executed: line and set the date.

5. The ledger merge runs inside each rebuild, and its line should read ledger-v2 … [<floor>, <tip>] without DEFERRED: these wallets' bare-token coverage is certified down to their floors already. A DEFERRED line is not a failure of this step — the drain re-checks every tick and derives once the enrolment lands — but note which wallet it happened on, because until it derives that wallet has a spine and no receipts.

Rollback. There is none to take, and none is needed. The rebuild produces the wallet's history under the corrected rule, which is more history than it had and the same data where they overlap; a code revert would not shorten a chart already rebuilt, and shortening one by hand would be re-introducing the defect on that wallet.

The PT row's pre-window fills: first deploy (migration 113) ​

  • belongs to: migration 113 (a held PT's real pre-window router fills, docs/plans/pt-row-attribution-plan.md D2c) — the release carrying feat/pt-row-attribution
  • executed: 2026-09-23

Applied 2026-09-23 17:57:56Z on prod (v0.69.0), after the deploy, by migrate.sh; schema_migrations records it (read back 2026-09-24 during the v0.70.0 release).

113 is ADDITIVE: one new table, portfolio_pt_prewindow_fills, FK-cascaded from accounts, with grants for both app roles. Staging auto-applies it on the merge deploy. On prod it is the usual gated manual step, and it may run AFTER the deploy: the code tolerates the table's absence on both sides (the wallet build reports table absent (migration 113 not applied), nothing stored and the loader reads no fills), so the only cost of a late apply is that wallets built in between keep the stand-in lot for PTs held since before their window until their next build.

bash
ssh -i ~/.ssh/hetzner_ed25519 root@dexhq.io
cd /opt/onchain-credit && scripts/ops/migrate.sh "$(grep ^DATABASE_URL= .env.local | cut -d= -f2-)"
sudo -u postgres psql -d creddit -At -c "SELECT to_regclass('onchain_credit.portfolio_pt_prewindow_fills'), has_table_privilege('onchain_credit', 'onchain_credit.portfolio_pt_prewindow_fills', 'INSERT')"
# expect: onchain_credit.portfolio_pt_prewindow_fills|t

No backfill and no re-derive. Everything else in the release is read-time or forward-only: the PT receipt stamps (meta.ptFactor / ptRate / ptMarkValue) are written by every derivation from the deploy on, and a row derived before them reads exactly as it did (the lot book falls back to the stored factor series, and to the coin count or the row's dollar value for the price). What that means on the page until the wallet's next full build re-derives its ledger: the PT row's open position is stated in full except that its mark to market stands unsplit (a lot bought before the deploy has no market yield at its purchase on file), and a purchase paid in a coin other than the payout coin keeps its rate struck from its dollars at $1, a few basis points off. Nothing reads as a dash for want of a stamp. A wallet added after the deploy gets all of it on its first build.

GATED STEP: re-judge the stored price history against both vendors ​

  • belongs to: the re-judge repair (scripts/repair/rejudge-price-bars.ts, branch feat/price-rejudge) — the release carrying it
  • executed: 2026-09-24

Run end to end on prod 2026-09-24 (v0.70.0, merge 8e465826, deployed 16:27Z), on Fred's go in session. Step 2 was taken FIRST, read-only with the cron still running (16:29-16:39Z; END 2026-09-22T16:00Z; 94 CoinGecko + 1,006 DefiLlama requests, 0 Dune credits), so that the cron was drained only for the writes: nothing the cron writes can reach an hour at or before END. Step 1 drained the 18 prod lines at 16:39:37Z, and step 2 re-run from the cache with the cron drained planned the identical 1,875 retractions, 4,148 fills and 1,738 basis rows. That is the reviewed report's plan exactly, bar one extra spike-refused UNI candidate, which writes nothing. Step 4 (dump /root/rejudge-pre-20260924T165025.sql) committed 52 tokens with no rollback: 1,875 retracted, 1,884 retracted rows replaced, 4,148 bars inserted, 1,738 token_basis rows rewritten, 0 errored; one wallet (0xe51d…3ed9, via AUSD) queued. Step 5: the re-run plans 0 / 0 with nothing owed; AUSD Sep 3-10 now tops out at $1.00032 (181 coingecko:hourly + 11 tape bars); apyUSD Aug 27 - Sep 15 reads $1.350-$1.383; 4 convicted hours stay unfilled (vendor split or dark). Step 7 ran BEFORE step 6, with the cron still drained as the re-mark's own procedure requires, and scoped to --wallet=0xe51d…3ed9 and AUSD's three consumer assets (the --tokens=AUSD dry run's list) rather than the full report's 185-asset union, which covers every changed token although only AUSD's hours were read by a stored row: 7 snapshot rows (Sep 4-10) went from $65.1M-$154.6M to $3.69-$4.20, and a second run repaired 0. Step 6 restored the crontab at 16:51:36Z (identical to the backup; drained for 12 minutes), and the wallet's cursor was back at 16:52Z (launched=1 stamped=1 failures=0). The state files, the dump and every log are in /root.

Runs once, on prod, after the release that carries the script, and only on Fred's explicit go on the dry-run report posted to the pull request. Staging can rehearse it — its bars are prod's as of the nightly reseed — and the rehearsal is wiped by the next reseed; remove its state with it (rm /var/tmp/rejudge-price-bars/*-creddit_staging.jsonl /root/rejudge-end-creddit_staging), or a later staging run replays follow-up for writes the reseed undid.

Why the release is not enough on its own. The six-hourly leg judges a bar as it arrives and fills an hour that goes missing, inside its own 48-hour window, and it has only run since v0.68.0. Every bar accepted before that was never judged, so the stretches found on 2026-09-21 were still stored and served: AUSD at $17.7M-$36.8M for 181 hours (Sep 3-10), apyUSD at $0.85-$1.09 against about $1.36 (Aug 27 - Sep 15, partly retracted on 09-23), FBTC (Aug 17-20, Sep 18-19), eBTC (Aug 19), ETHx (Aug 28) and osETH (Jun 27-29). Any wallet whose 30-day window reaches one of them marks off it. The rules and what the repair does are in Re-judging the stored history.

1. Drain the cron. Every prod run-cron.sh line, because three of them write what this step writes or reads (the six-hourly refresh-assets writes bars and retracts, the portfolio tick and the minutely drain mark off bars and stamp derive cursors), and a plan read while one of them runs is refused token by token. Staging's lines, the backup and the reseed are left alone.

bash
crontab -l > /root/crontab.bak-rejudge
crontab -l | sed 's|^\([^#].*/opt/onchain-credit/scripts/run-cron.sh .*\)$|# REJUDGE \1|' | crontab -
crontab -l | grep '/opt/onchain-credit/scripts/run-cron.sh' | grep -vc '^# REJUDGE'   # expect 0
pgrep -af '/opt/onchain-credit/scripts/' || echo idle   # wait until nothing of prod's is running

2. Dry run, read-only, with a fixed end and a vendor cache. The end and the cache are what make step 4 write exactly what step 3 reads: the execution plans from the same stored bars (the cron is drained) and the same vendor answers (the cache), so a vendor restating history in between cannot change what is written. The end is written to a file the first time this block runs and read back every time after, so re-running the block, in any shell, on any day, judges the same window.

bash
cd /opt/onchain-credit
[ -s /root/rejudge-end-creddit ] || date -u -d '48 hours ago' +%Y-%m-%dT%H:00:00Z > /root/rejudge-end-creddit
END=$(cat /root/rejudge-end-creddit); echo "$END"
mkdir -p /var/tmp/rejudge-cache && chmod 1777 /var/tmp/rejudge-cache
(set -a; . ./.env.local; set +a; \
  PGOPTIONS='-c default_transaction_read_only=on -c statement_timeout=600000' \
  node_modules/.bin/tsx scripts/repair/rejudge-price-bars.ts --to="$END" \
  --vendor-cache=/var/tmp/rejudge-cache) 2>&1 | tee /root/rejudge-dryrun-$(date -u +%Y%m%dT%H%M%S).log

It takes about half an hour (roughly 19 keyless DefiLlama requests a token, and CoinGecko only over spans holding a suspect bar or a gap), buys no Dune credits, and writes nothing. The statement timeout turns a hung query into a failure rather than a wait.

3. Read the magnitude. If it is not what the report on the pull request said, STOP. Per token: bars judged, bars to retract, hours to fill and what each replaces, and every retraction with its hour and the three prices. The plain stables the tape and the vendors agree about (USDC, USDT, DAI, …) must show retract 0. A [partial] line means a vendor could not be asked about some span; re-run step 2's block (the cache keeps every answer already had, and the end is read back from its file) until it is gone.

4. Back up, then execute as the table OWNER (a refill deletes the retracted row it replaces, and 055 revoked DELETE from the app role), over the same end and cache, --offline so nothing is asked twice. Nothing else in this file runs tsx as postgres, so the first line checks that it can, before anything is written:

bash
cd /opt/onchain-credit && sudo -u postgres node_modules/.bin/tsx --version   # must print a version
END=$(cat /root/rejudge-end-creddit); echo "$END"                          # step 2's end
sudo -u postgres pg_dump -d creddit --data-only -t onchain_credit.token_price_bars \
  -t onchain_credit.token_basis -f /var/tmp/rejudge-pre-$(date -u +%Y%m%dT%H%M%S).sql
sudo -u postgres env DATABASE_URL="postgres://postgres@/creddit?host=/var/run/postgresql" \
  PGOPTIONS='-c statement_timeout=600000' \
  node_modules/.bin/tsx scripts/repair/rejudge-price-bars.ts --execute --confirm-db=creddit \
  --to="$END" --vendor-cache=/var/tmp/rejudge-cache --offline \
  2>&1 | tee /root/rejudge-execute-$(date -u +%Y%m%dT%H%M%S).log
cp /var/tmp/rejudge-price-bars/rejudge-*-creddit.jsonl /var/tmp/rejudge-pre-*.sql /root/

Each token is one transaction. Before it commits, the rows a refill deletes are appended to /var/tmp/rejudge-price-bars/rejudge-deleted-creddit.jsonl and the hours it wrote to rejudge-changes-creddit.jsonl beside it; a failure to write either rolls the token back. Both are named by the database and moved by no flag, so every later run on this database finds them. They are written under /var/tmp because the execution runs as postgres, which cannot write /root, and /var/tmp is swept after 30 days, so the block's last line copies them and the dump to /root, where the logs already are. A [fail] line names a token that rolled back (its stored rows moved since the plan, because something wrote while the cron was meant to be drained, or it threw): nothing of that token was written. Find the cause, then re-run step 4's block without --offline (the end is read back from its file; the cache still answers every span it holds, and only what the repaired history now asks differently is fetched; each run keeps its own dump). A re-run plans nothing for a token already repaired, finishes the basis recompute and the wallet step over every logged write that step has not yet completed, and never repeats a step that completed, so a wallet already queued is not queued a second time.

5. Verify. Re-run step 2's block (it reads the same end back): every token must now plan retract 0 and fill only what it could not fill before (a vendor split, a dark hour), and no [partial] line may say the change log still owes follow-up. Then the headline stretch:

sql
-- read-only. The AUSD September stretch: no bar above a dollar and a cent remains accepted.
SELECT source, rejected, count(*), max(price_usd)
  FROM onchain_credit.token_price_bars
 WHERE chain_id = 1 AND token_address = '0x00000000efe302beaa2b3e6e1b18d08d69a9012a'
   AND bar_ts >= '2026-09-03' AND bar_ts < '2026-09-11'
 GROUP BY 1, 2;

6. Restore the cron. crontab /root/crontab.bak-rejudge. The report's wallet line has two halves. The wallets it queued are re-derived by the minutely drain's re-derivation trigger, two a minute: each had its derive cursor removed (only after the trigger's own gates said it would come back for it), and while it has none its ledger is withheld from the page (minutes). Watch /tmp/onchain-credit-cron/onchain-credit-drain-portfolio-backfills.log and confirm each cursor is back (SELECT scope FROM onchain_credit.chain_scan_cursors WHERE scope LIKE 'portfolio:derive:v2:1:%'). The wallets it named as not queued kept their cursors, because the trigger would not have come back for them (the reason is printed beside each): re-derive each by hand, ranged from its own floor to its own cursor, in the shape the forced-pull step spells out.

7. The snapshot half. Retired by the contract release, step 2 (issue #981, PR #1011, its entry): a reading stores no money value since migration 129, so a re-judged bar re-values every reading at the next read and there is nothing to re-mark; the re-mark tool below is deleted. A re-run skips this step. The step as it stood before 129 (and ran on 2026-09-24): if the report named wallets, their stored SNAPSHOT marks still carry the old prices, which the re-derivation does not restate. Run it BEFORE step 6, while the cron is still drained (the re-mark's own procedure drains first). The report's --assets= list is the union over every changed token; narrow it to the tokens printed beside the named wallets: a --tokens=<those> dry run over the same end and cache prints their list. Then run the category-flip re-mark once per named wallet, dry run first: scripts/run-cron.sh repair/remark-snapshot-marks.ts --wallet=<w> --assets=<that list>, then --execute; a second dry run must repair 0. If WETH is among those tokens, every ETH-book asset's snapshots are in scope too.

8. Record the run here: the date in executed:, and the summary lines of step 4's log. Then rm /root/rejudge-end-creddit; keep the /root copies of the two state files and the dump until the release after next.

Rollback. The deleted rows are in rejudge-deleted-creddit.jsonl, the hours written in rejudge-changes-creddit.jsonl, and the whole of both tables in the step-4 dump, all three copied to /root at the end of step 4 (the originals under /var/tmp are swept after 30 days). To undo a token by hand, as the owner: delete its coingecko:hourly / llama:chart bars at the logged hours, re-insert the backed-up rows, and set rejected = false on the bars the run retracted (reject_reason LIKE 'vendor-disagreement-rejudge%'); then restore token_basis for those hours from the dump. There should be no reason to: every retraction is two vendors agreeing, and step 3 is where to refuse one.

GATED STEP: open every enrolled wallet at its window start, and restate 0xef08…'s ether (the 2026-09-28 rule) ​

  • belongs to: the window-start openings fix (branch fix/opening-at-window-start, off v0.72.0), the release after v0.72.0
  • executed: 2026-09-28

Run 2026-09-28 on prod (v0.73.0, release PR #980, merge 24973735, deployed 20:29:26Z), on Fred's go. Step 0 (20:38Z): 0xef08…'s ether held the one hand-accepted adjustment at 25,986,307 (109951945780933501) and no opening; the pre-history corrections were 1, not 2, because 0xe51d…'s PYUSD one had gone at 20:36Z, removed by the audit the wsrUSD step 4 re-derive queued (its worker opening before the first movement, the "either state is fine" case). Step 1, the dry run (20:38:12Z): opening-backfill: DRY RUN (nothing written; pass --apply); wallets 8 (skipped 0); openings to write 15 (of which dust, hidden on the surfaces, 1), already present 102; re-audits queued 0; read from the chain 15; redundant openings removed 0; legs the chain could not state 0. The from the chain list (/root/opening-window-start-from-chain.txt) is 15 lines: 0xef08…'s ETH 0.109951945781, sUSDe 9,044.68, wstETH 10.93, GHO 16.70, WBTC 0.00102371 and reUSD 67.66 at 25,835,658 (no USDC, no Aave supply); 0xaae6…'s WBTC 0.00009195 and cbBTC 0.09479236; 0xb47c…'s sUSDai 0.00000018 (the dust one) and USDT 14.18; 0xb8b8…'s USDC 1.33; 0xe159…'s USDC 11.77; 0xe51d…'s PYUSD 21.35, RLUSD 35.65 and crvUSD 3.21, each at its wallet's floor. No not stated line, and every leg listed has ledger rows (the stop check). Step 2 (20:39:06Z): opening-backfill: APPLIED; wallets 8 (skipped 0); openings written 15 (of which dust, hidden on the surfaces, 1), already present 102; re-audits queued 6; read from the chain 15; redundant openings removed 3; legs the chain could not state 0 (the 3 are 0xe51d…'s first-movement openings); the second apply read openings written 0 (of which dust, hidden on the surfaces, 0), already present 117; re-audits queued 0; read from the chain 0; redundant openings removed 0. Step 3: the six re-audits (#169 to #174) ran 20:39:16 to 20:39:58Z, each partial on unread legs alone, with 0 openings and 0 adjustments booked: 0xaae6… 22 unread, 0xb47c… 68, 0xb8b8… 27, 0xe159… 6, 0xe51d… 48, 0xef08… 3. 0xef08…'s lines: reading @25986307: absent=3 agree=2; 0 row(s) booked, 0 restated, 1 removed, its WBTC, GHO and reUSD unread at 25,986,307 and 25,993,482 as expected, then rows above a correction re-derived over [25986308,26077852] (continuous job #178, done, 0 written); no unexplained line in the worker's log. The same re-audits removed the five accepted native-eth-transfer corrections (0xaae6… at 25,936,090, 0xb47c… at 26,070,439 and 26,075,555, 0xe159… at 25,878,705 and 26,000,651), each after native-ether break … row(s) found, sources complete. Decoder gaps: none (no read directly: zero line). Step 4 (20:40:45Z): the ether's one audit row is the opening at 25835658, qty_delta = to_balance = 109951945780933501, anchor floor; pre_history_corrections is 0, and no adjustment row of any cause is left on prod (7 before: 5 accepted native-ether, 2 hand-accepted). Openings: 15 floor over 6 wallets beside the 102 unanchored. The hourly alarm's four arms read ok at 20:40:36Z (ledger-audit: ok: no unexplained adjustment, no leg unread twice). The page, read through its own builders with the capture harness (golden-portfolio.ts --db-url, read-only sessions, network refused): 0xef08…'s chart starts 2026-09-16 00:00Z in all six views, and its statement lists the September fees ("Gas paid (action not covered by creddit)", "Gas fee paid") with no adjustment entry in any of its six activity reads.

What it repairs. Every position gets an opening at the wallet's window start (the account's history floor block), read from the chain, so every later movement reconciles against it (the rule). The release writes those openings for every wallet enrolled from then on and, through the worker, for a leg whose first movement precedes every opening; the wallets enrolled before it keep the openings the ledger-first backfill wrote at their FIRST READING. For the six prod accounts whose chart starts at their floor that is the same block; for 0xef08c6a47c04764b9c0964e00bd01c3e200707c5 it is not. Its floor is block 25,835,658 (2026-08-26) and its first reading 25,986,307 (2026-09-16), because it held only idle balances and ether at its floor (#931 raised its chart's start). The native-ether feed (#967) landed its fees and transfers from block 25,852,664, below the first reading; the ledger had no opening under them; the audit at 25,986,307 removed the ether opening the backfill had written there and booked +0.109952 ETH (109,951,945,780,933,501 wei, the balance before its first in-window fee) as an UNEXPLAINED correction. That row was hand-marked accepted with cause pre-history-balance (hand-accepted 2026-09-28 pending the opening fix, #966 follow-up) to stop the hourly page. This step restates it: the extended backfill reads the wallet's holdings at its floor from the chain, and the re-audit it queues removes the hand-accepted row.

A prod write: take it with explicit approval, after the release is deployed (the worker must run the release's code: the re-audits are its jobs). Run on prod only; staging reseeds from prod's dump nightly and holds nothing for it to act on.

0. Before. The wallet's ether audit rows, and every hand-accepted pre-history correction:

bash
cd /opt/onchain-credit
set -a; . ./.env.local; set +a
W=0xef08c6a47c04764b9c0964e00bd01c3e200707c5
sudo -u postgres psql -d creddit -c "
  SELECT kind, block_number, qty_delta, to_balance, explain_status, cause, meta->'audit'->>'anchor' AS anchor
    FROM onchain_credit.portfolio_flow_events_v2
   WHERE chain_id = 1 AND wallet = '$W' AND position_key = 'wallet:token:0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'
     AND kind IN ('opening', 'adjustment')
   ORDER BY block_number"
sudo -u postgres psql -d creddit -c "
  SELECT wallet, block_number, position_key, qty_delta FROM onchain_credit.portfolio_flow_events_v2
   WHERE chain_id = 1 AND kind = 'adjustment' AND cause LIKE 'pre-history-balance%'"

Expected on 2026-09-28: one adjustment at 25986307 (qty_delta 109951945780933501, accepted, the hand-accepted cause), and no opening. After the deploy the worker may already have moved this on: its first derivation or audit job for the wallet reads the ether before the first fee (the rule's second half: an opening at 25852663 with anchor first-movement, 109951945780933501 wei) and queues a re-audit that removes the correction. Either state is fine; step 2 moves every opening to the window start and step 4 checks the end state.

1. Dry run, the whole population. It reads the chain where no stored reading stands at a wallet's floor (0xef08's) and for the legs a floor reading does not hold; production's ETHEREUM_RPC_URL (Alchemy) serves the past blocks it asks about. Nothing is written:

bash
npx tsx scripts/ops/backfill-opening-rows.ts --db-url "$DATABASE_URL" | tee /tmp/opening-window-start-dry.log
grep -E "would write|not stated|skipped" /tmp/opening-window-start-dry.log
tail -1 /tmp/opening-window-start-dry.log
grep -F " from the chain key=" /tmp/opening-window-start-dry.log | tee /root/opening-window-start-from-chain.txt | wc -l

Keep /root/opening-window-start-from-chain.txt: the dry run's from the chain lines, one per leg this step opens from a read of the chain rather than from a stored reading (its wallet, leg, block and quantity). It is the list step 3 compares the worker's lines against, and step 5 records it. Read the dry run before step 2. Expected for 0xef08: would write … wallet wallet:token:0xeeee…eeee block=25835658 qty=109951945780933501 (0.109951945781 ETH, …) from the chain key=0x…, and one line per other leg it held at its floor (on the ledger's own evidence: sUSDe, wstETH, GHO, WBTC and reUSD, each sold in the window); no line for its USDC (created from nothing on 2026-09-04) or its Aave supply. For every other wallet, only legs its floor reading did not hold that the chain held at the floor (the ledger's own evidence names 0xaae6…'s WBTC and cbBTC, 0xb47c…'s sUSDai and USDT, 0xb8b8…'s and 0xe159…'s USDC and 0xe51d…'s PYUSD, RLUSD and crvUSD as legs whose first movement moved an unstated holding; the chain decides which were held at the floor). A not stated line is a leg the chain did not answer for: nothing is written for it, and the worker's rule-2 read asks again. Stop if a would write names a leg the wallet's ledger has no row for and no reading holds.

2. Apply, then again.

bash
npx tsx scripts/ops/backfill-opening-rows.ts --db-url "$DATABASE_URL" --apply | tee /tmp/opening-window-start-apply.log
tail -1 /tmp/opening-window-start-apply.log
npx tsx scripts/ops/backfill-opening-rows.ts --db-url "$DATABASE_URL" --apply | tail -1

The first APPLIED line's written count is the dry run's (less any leg a worker job opened at its floor meanwhile), redundant openings removed counts the worker's first-movement openings the floor openings replaced, and re-audits queued names one job per wallet changed. The second line reads openings written 0 and re-audits queued 0: idempotent, and an opening already at or below a floor is never rewritten.

3. The re-audits, on the worker (pm2 creddit-ledger-worker; nothing to start). Done when none is left open:

bash
sudo -u postgres psql -d creddit -c "
  SELECT wallet, from_block, to_block, state, left(coalesce(error, ''), 160) AS error
    FROM onchain_credit.portfolio_derive_jobs
   WHERE chain_id = 1 AND kind = 'audit' AND created_at > now() - interval '2 hours'
   ORDER BY id"
pm2 logs creddit-ledger-worker --lines 400 --nostream | grep -E "ledger-audit\] $W|ledger-openings\]|\[partial\] ledger audit"

Expected for 0xef08: reading @25986307: agree=… ; 0 row(s) booked, 0 restated, 1 removed (the hand-accepted correction), no unexplained adjustment line. An unread line at 25986307 and 25993482 for its GHO, WBTC and reUSD legs is expected and the job then ends partial: those tokens were held there and no reading read them (the replay's universe did not include them), which R8c reports now that the ledger holds what the chain held; the hourly arm does not page it (it judges a wallet's newest two readings, where the ledger holds none of them). The same holds for any wallet whose never-read leg was held at a past reading. A never-read leg still HELD at a new reading pages through the arm (R8c), which is a reader failure to investigate (§11 of the ledger-first plan).

A direct read of ZERO after an opening is a decoder gap to investigate, not a failed repair. Compare the worker's lines with step 1's list:

bash
pm2 logs creddit-ledger-worker --lines 2000 --nostream | grep -F "read directly: zero"

A line there for a leg on /root/opening-window-start-from-chain.txt (an exit correction booked on it, an adjustment to zero at a reading after the floor, paged where unexplained) means the chain held the leg at the floor, this step opened it there, and the leg is gone at the reading while the ledger records no movement that took it out. Counted from zero before this step, that leg never went above zero, so the gap was invisible; now the missing movement shows as the exit correction. The opening is right (it is the chain's own balance at the floor) and so is the correction (the chain's own zero): leave both, and investigate which transaction moved the leg and which stream should have decoded it. 0xef08's WBTC and reUSD are the shape to expect it on (a first movement that sold a holding no row stated); those two are fine, their sales are recorded. Note each such wallet, leg and block range in the record (step 5).

4. After. Step 0's two queries again:

bash
sudo -u postgres psql -d creddit -c "
  SELECT kind, block_number, qty_delta, to_balance, explain_status, cause, meta->'audit'->>'anchor' AS anchor
    FROM onchain_credit.portfolio_flow_events_v2
   WHERE chain_id = 1 AND wallet = '$W' AND position_key = 'wallet:token:0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'
     AND kind IN ('opening', 'adjustment')
   ORDER BY block_number"
sudo -u postgres psql -d creddit -c "
  SELECT count(*) AS pre_history_corrections FROM onchain_credit.portfolio_flow_events_v2
   WHERE chain_id = 1 AND kind = 'adjustment' AND cause LIKE 'pre-history-balance%'"

It holds when the ether's one audit row is the opening at 25835658 (qty_delta = to_balance = 109951945780933501, anchor floor) and the count is 0. Then load 0xef08 on /portfolio: its chart still starts on 2026-09-16, and its activity lists the September fees without a "Balance adjustment" line.

5. Record the run here: the date in executed:, the dry run's and the apply's summary lines, the count of step 1's from the chain list, step 3's worker lines for 0xef08, and every decoder gap step 3 found (wallet, leg, block range).

Rollback. None owed: the openings are insert-only, keyed, and read from the chain at their block; the rows the re-audits removed are what the ledger no longer needs (an opening at or below each states the holding). To undo a wallet's floor openings by hand, delete its kind = 'opening' AND meta->'audit'->>'anchor' = 'floor' rows and queue a re-audit from its floor (the audit then opens each leg at its first reading again, the rule before this release).

GATED STEP: bring back the two weETH-only wallets the ether.fi route proof refused (#1010, PR #1065) ​

  • belongs to: the ether.fi/Lido helper-route fix and the queue route hold-back (issue #1010, PR #1065), the release that ships it
  • executed: 2026-10-08

What it changes for a user, in one line: two wallets that have read "Building your portfolio history" since v0.79.0 get their history, with every ether.fi withdrawal shown as an ordinary position in settlement.

Why a step at all. Every whole-history derivation of 0xdd647ce113505b34c62412d2a804ce1bfbcfc737 and 0xd1a557fe9d49d047a2318c05a13523e4b9e56e09 ended partial on "request source route cannot be proven", so after the release they may be at the re-derivation attempt cap (the trigger stops retrying at 5) or quarantined from the 6h sweep. The cap does not clear by itself; a quarantined wallet rejoins on its first clean sweep once the route is fixed, and step 2 only brings that forward. The same step is the standing manual procedure (Fred, 2026-10-08) for any later release that teaches the route proof a route: a wallet already stamped with held-back queue rows is not re-derived automatically, so the release that fixes its route re-queues it here.

1. Read their state (prod, read-only):

bash
sudo -u postgres psql -d creddit -c "
  SELECT scope, last_scanned_block, updated_at FROM onchain_credit.chain_scan_cursors
   WHERE chain_id = 1 AND (scope LIKE 'portfolio:derive:v2:1:0xdd647ce113505b34c62412d2a804ce1bfbcfc737%'
      OR scope LIKE 'portfolio:derive:v2:1:0xd1a557fe9d49d047a2318c05a13523e4b9e56e09%'
      OR scope IN ('portfolio:v2-campaign:rederive-attempts:0xdd647ce113505b34c62412d2a804ce1bfbcfc737',
                   'portfolio:v2-campaign:rederive-attempts:0xd1a557fe9d49d047a2318c05a13523e4b9e56e09'))
   ORDER BY scope"

A wallet with a rederive-attempts row at 5 is at the cap. A wallet whose derive cursor row (portfolio:derive:v2:1:<wallet>, no suffix) already exists has stamped: go to step 3. The cursors cannot say whether a wallet is quarantined; its sweep jobs can. A :jit-pending row above plus its newest N sweep jobs all partial here (N is LEDGER_QUARANTINE_AFTER_SWEEPS, default 2; a partial whose reason starts closed: ends a run rather than lengthening it) means it is quarantined:

bash
sudo -u postgres psql -d creddit -c "
  SELECT wallet, state, created_at, left(error, 160) FROM onchain_credit.portfolio_derive_jobs
   WHERE chain_id = 1 AND kind = 'sweep' AND state IN ('done','partial','failed')
     AND wallet IN ('0xdd647ce113505b34c62412d2a804ce1bfbcfc737',
                    '0xd1a557fe9d49d047a2318c05a13523e4b9e56e09')
   ORDER BY wallet, created_at DESC"

2. Re-queue each wallet that has not stamped: delete its rederive-attempts row (the counter is never reset in place, only deleted) so the trigger may launch again, or enqueue one whole-window rederive by hand exactly as the runbook states it (from_block the wallet's own floor, to_block the chain head). Deleting the attempts row re-launches only a wallet the trigger takes as a candidate (one that holds ledger rows or a deferred marker), so after deleting it confirm a rederive job for the wallet appears in portfolio_derive_jobs within a few minutes (the trigger runs every minute); if none does, enqueue it by hand. A wallet that already has an open enrol or rederive job gets no second one: wait for that one instead. One job per wallet; wait for it to finish.

3. Check each wallet stamped with nothing held back:

bash
sudo -u postgres psql -d creddit -c "
  SELECT wallet, count(*) FILTER (WHERE meta->>'withheld' = 'queue-route-unproven') AS held_back,
         count(*) FILTER (WHERE venue = 'escrow') AS escrow_rows
    FROM onchain_credit.portfolio_flow_events_v2
   WHERE chain_id = 1 AND wallet IN ('0xdd647ce113505b34c62412d2a804ce1bfbcfc737',
                                     '0xd1a557fe9d49d047a2318c05a13523e4b9e56e09')
   GROUP BY wallet"

It holds when both derive cursors exist, held_back is 0 for both, escrow_rows is not, and the next ledger self-check names neither wallet. Then load each on /portfolio: the building state is gone and the ether.fi tickets read In settlement (or paid).

4. Record the run here: the date in executed:, step 1's rows per wallet and step 3's counts.

Run of 2026-10-08 (prod, v0.83.0 = 827c61c1, deployed ~12:49 UTC):

  • Step 1 (read after the ~12:49 UTC deploy and before the 12:55:54 re-queue; the exact read time was not recorded). Both wallets had portfolio:v2-campaign:rederive-attempts:<wallet> = 5 (at the cap), a :jit-pending row (0xdd64… at 26,139,291, 0xd1a5… at 26,139,332) and a :followed-after row (26,146,506 / 26,146,560); 0xdd64… also had :settled-through 26,147,657. Neither had a plain derive cursor row.
  • Step 2. Both rederive-attempts rows deleted at 12:55:54 UTC; the drain's trigger enqueued one whole-window rederive per wallet at 12:56:02 ([25,928,920, 26,147,752]). Job #1459 (0xd1a5…) done in 34.1 s, about 12:56:36 (202 written, 1,162 unchanged, 0 removed); job #1460 (0xdd64…) done in 22.9 s, about 12:56:59 if it ran after #1459 (6 written, 685 unchanged, 0 removed). The two completion times are derived from the enqueue time and the durations, not read.
  • Step 3. Derive cursors exist for both at 26,147,752; held_back = 0 for both; escrow_rows = 22 (0xdd64…) and 202 (0xd1a5…). 0xdd64…'s three ether.fi tickets (82547, 82578, 83253) are booked pending → paid. /api/portfolio/summary shows backfill: "done", syncing: false for both, and the served positions carry no returnWithheld. Open positions served for 0xdd64…: the sUSDe cooldown (~$600.6k) and Lido tickets 137965 / 138031 / 138060 (~$4.67M) under Variable rate assets.

Rollback. None owed: a re-derivation writes the wallet's own ledger rows only, idempotently.

GATED STEP: re-derive the wallets whose queued-redemption requests predate the one-value rule ​

  • belongs to: the queued-redemption request valuation fix (a request's departing holding valued at the ticket it becomes; every consideration-valued row stamped for the page), the release that ships it
  • executed: 2026-10-08
  • run record: (v0.84.0, deploy 736a6299 at ~22:58 UTC; run at 23:01–23:02 UTC). Step 1 named exactly the two documented wallets: 0xd1a557fe…6e09 104 old-shape rows, 0xdd647ce1…c737 21. Step 2: one whole-window rederive per wallet (jobs #1588 and #1589, [25928920, 26150828]): #1588 done in 25.7 s (21 written, 1390 unchanged, 0 removed), #1589 done in 32.5 s (104 written, 1306 unchanged, 0 removed). Step 3: the step-1 query names no wallet; no held-back row on either; derive cursors 26150760 / 26150765. Summaries (POST refresh then GET summary; the "before" is the cached live read of the old-shape rows): 0xd1a5… ETH book market cumulative yield −0.2539 → +0.4267, redemption 0.1225 → 0.1228, book value 277.26 unchanged (the 30-day window had rolled since the −0.60 estimate). 0xdd64… ETH book market −0.1452 → +1.2146, redemption 0.0508 → 0.0508 (its book value 1301 → 1103 is the wallet's own activity at 21:30 UTC: 201 ETH sent out, a 103 ETH Lido request, 100 WETH into Aave; not the re-derive). 0xdd64… USD book: market 4960.53 → 4970.87 and redemption 3048.94 → 3059.29, i.e. both lines +10.3 (an interval of accrual); the Ethena cooldown's discount expected on the market line (the "about 865 USD" above) did not show, although the sUSDe departure rows now carry valuationBasis = consideration (value_market 500,204.91 / 600,517.39 against swap-in rows at 499,976.13 / 600,166.30). Under read-only investigation; recorded here as observed, not as expected.

What it changes for a user, in one line: a holder who sent a token trading below par to a redemption queue sees the discount they captured as a gain on that holding, instead of a loss.

Why a step at all. The rule is a writer change: the departing holding's row now states the ticket's entitlement as what it is valued at (consideration_asset, consideration_raw, meta.valuationBasis = 'consideration'), and the read path values a stored row from those facts. The same release stamps meta.valuationBasis on the other rows a writer values at their consideration and used to leave unstamped: a cancelled Syrup request or manual release, a queue payout converted on its way to the wallet, and the received side of a mint or wrap. Rows written before the release state none of this, so their wallets keep the old figure until re-derived. Counted on prod 2026-10-08: two wallets. 0xd1a557fe9d49d047a2318c05a13523e4b9e56e09 (103 ether.fi request rows; ETH book cumulative yield, market line, −0.60) and 0xdd647ce113505b34c62412d2a804ce1bfbcfc737 (Lido, ether.fi, Ethena and Maple requests, and one wstETH mint). Syrup cancellations and manual releases: 0 rows. Converted queue payouts: 0 rows.

1. Name the wallets (prod, read-only):

bash
sudo -u postgres psql -d creddit -c "
  SELECT wallet, count(*) AS old_shape
    FROM onchain_credit.portfolio_flow_events_v2
   WHERE chain_id = 1 AND meta->>'valuationBasis' IS NULL
     AND ((venue = 'wallet' AND kind = 'internal_out' AND meta->>'escrowEvent' IN ('request', 'RequestRedeem'))
       OR (coalesce(consideration_asset, '') <> '' AND consideration_raw IS NOT NULL))
   GROUP BY wallet ORDER BY wallet"

2. Re-derive each wallet it names: one whole-window rederive per wallet, exactly as the runbook states it (from_block the wallet's own floor, to_block the chain head). One job per wallet; wait for it to finish.

3. Check: step 1's query names no wallet, except for a by-design unstamped row (an f(x) request that stated no amount keeps its burn's own mark: look at any such row's meta before re-running). Each wallet's summary moves on the market line, with the redemption line unchanged to within the rounding between a token's redemption rate and the queue's stated entitlement. Expected on the 2026-10-08 data: 0xd1a5… ETH book market cumulative yield from −0.60 to about +1.06 (the 1.66 ETH of discount the window's requests captured), redemption +0.12; 0xdd64… ETH book market line up by the Lido and ether.fi discounts (about 1.39 ETH over the wallet's whole history, less inside the window), its USD book market line up by the Ethena cooldown's (about 865 USD) and the Syrup request's discount; book values unchanged on every book.

4. Record the run here: the date in executed:, step 1's rows and each wallet's summary before and after.

Rollback. None owed: a re-derivation writes the wallet's own ledger rows only, idempotently.

GATED STEP: index and backfill the sUSDai/USDC and sUSDai/USDT Fluid DEX pools ​

  • belongs to: the sUSDai DEX-pool registration (branch feat/susdai-dex-pools, with the feat/susdai-pools entry in the creddit-indexer repo), the release that ships it
  • executed: 2026-10-09
  • run record: (v0.85.0, release PR #1097, merge b520bbdb, deploy run 37970504638 green; the app restarted on 0.85.0 at 18:03:42Z; migrate.sh at 18:04Z applied 132 to 136, five files). Step 2 (18:06Z to 18:09Z): sUSDai-USDC DONE: 469 rows in [25268517, 26155040]; last back-filled swap at 26153766, sUSDai-USDT DONE: 379 rows in [25268589, 26155040]; last back-filled swap at 26154018, both exit 0. The check: swaps = distinct_logs (469 / 379), first swaps at 25,315,900 and 25,338,122; the chain has no Swap log on either pool between its creation and those blocks (an independent eth_getLogs read), so the history starts at the first trade, about a week after creation. Above the seam the indexer holds exactly the four swaps the chain shows (sUSDai-USDC, blocks 26,156,553 to 26,156,584); none on sUSDai-USDT. Step 3 (18:09Z to 18:15Z): DONE - 992 rows written, 0 failed. The check: 496 windows per pool, 2026-06-08 00:00 to 2026-10-09 18:00, unpriced 27 per pool (the last at 2026-06-14 12:00), no_per_share 0, average fee APY 0.141% (USDC) and 0.077% (USDT). no_swap_windows is 338 and 361 of 496, a majority rather than the minority the check expected: with 469 and 379 swaps in 496 windows most windows hold none, and the windows around the seam carry swaps (sUSDai-USDC 12:00 window 8, sUSDai-USDT 2), so no gap.
  • step 1 ran on prod: 2026-10-09 13:06 UTC, seam 26155040 (the record is under step 1); steps 2 to 5 wait for the release

What it changes for a user, in one line: the four sUSDai pool vaults (Fluid 175 sUSDai/USDC to USDC/USDT, 176 sUSDai/USDT to USDC/USDT, 177 sUSDai/USDT to USDT, 178 sUSDai/USDC to USDC, about $26M each) stop being held back for a missing pool, so the carry sync can propose them for /carries, each with its pool's trading-fee history. Swap volume and reserves go back to the pools' launch (2026-06-07); the dollar figures, and with them the fee yield, start at 2026-06-14 18:00 UTC, because sUSDai's first stored hourly price is 2026-06-14 13:00 UTC.

The pools (verified on chain 2026-10-09: FluidDexT1, created by the Fluid DexFactory 0x91716c4eda1fb55e84bf8b4c7085f84285c19085; fee 0.02%, revenue cut 25%, smart collateral only):

PoolAddressCreated at blocktoken0token1
sUSDai-USDC0xA2E3A4e2A08b5714FA974Ce88466D736BD8b39d925,268,517 (2026-06-07 22:30 UTC)sUSDai (18)USDC (6)
sUSDai-USDT0xb9b87A1B79891A8C9251F501B1b5d71bC7c8aA2425,268,589 (2026-06-07 22:45 UTC)sUSDai (18)USDT (6)

Both postdate the indexer's start block (25,221,291), and the indexer resumes from its own sync cursor, so every swap from creation to the restart below has to be filled from chain. Prod only: staging reseeds from prod nightly and runs no refreshers.

THE ORDER IS THE POINT: indexer first, then the release, then the two backfills straight after it. The live 6h tick starts writing both pools the moment the release reaches prod, and it sums whatever swaps the indexer has for each window. If the release went first, every window until step 2 would store swap_count = 0 and fee_apy_usd = 0 for both pools: a stored zero, not a blank. The Portfolio's 24h APY column for a wallet holding vault 175 to 178 would then show a confident, understated rate with the pool's trading fee missing (today it shows a dash), until step 3 rewrote those windows; and the carry sync would see the pools as snapshotted and could propose the vaults before any history existed. Deploying the indexer at least one full 6h window (plus the 5-minute lag) before the release means every window the live tick writes lies entirely above the seam, so it is complete from the first tick. The indexer reading two pools the app does not register yet is harmless: their swaps are only summed for registered pools.

The 6h wait is not required when steps 2 and 3 run straight after the deploy (Fred and the release coordinator, 2026-10-09, for the v0.85.0 release): step 3 replays the live writer through the current window, so it rewrites every window the live tick stored between the deploy and step 3, and the carry sync runs only after step 3. The wait matters only if the backfills are deferred.

0. Preconditions. The creddit-indexer PR (#2) is merged to master (done 2026-10-09). The release carrying this branch is NOT yet on prod.

1. Before the release: deploy the indexer, recording its cursor while it is stopped (that block is the seam). /opt/creddit-indexer on the box is a plain directory (rindexer.yaml, abis/, .env, README), not a git checkout: deploying the indexer means copying the committed rindexer.yaml from creddit-indexer's master over the live one. First put that file next to the live one, from any checkout of creddit-indexer at the merged commit:

bash
# on a machine with creddit-indexer checked out at the merged master
scp rindexer.yaml root@dexhq.io:/opt/creddit-indexer/rindexer.yaml.new

Then on the box:

bash
cd /opt/creddit-indexer
diff rindexer.yaml rindexer.yaml.new   # expect only the new pools' lines; anything else: stop and ask
pm2 stop creddit-indexer
sudo -u postgres psql -d creddit -Atc \
  "SELECT table_name FROM information_schema.tables WHERE table_schema = 'rindexer_internal' ORDER BY 1"
#   expect creddit_indexer_fluid_dex_pool_swap among them (the cursor table for FluidDexPool.Swap)
sudo -u postgres psql -d creddit -Atc \
  "SELECT network, last_synced_block FROM rindexer_internal.creddit_indexer_fluid_dex_pool_swap"
#   ethereum|<block>. Record it:
SEAM=<block>
cp rindexer.yaml "rindexer.yaml.bak-$(date -u +%F)"
mv rindexer.yaml.new rindexer.yaml
grep -c "sUSDai" rindexer.yaml         # expect 2
pm2 start creddit-indexer
pm2 logs creddit-indexer --nostream --lines 30   # no errors; syncing forward from the cursor

Wait until the cursor has moved past the seam (a minute or two):

bash
sudo -u postgres psql -d creddit -Atc \
  "SELECT last_synced_block FROM rindexer_internal.creddit_indexer_fluid_dex_pool_swap"   # > $SEAM

Step 1 record (2026-10-09 13:06 UTC, the release coordinator). Seam 26155040 (the FluidDexPool.Swap cursor, read while the indexer was stopped). The live rindexer.yaml was byte-identical to creddit-indexer master before the sUSDai PR (06ad285); origin/master's rindexer.yaml was copied over it (backup: /opt/creddit-indexer/rindexer.yaml.bak-2026-10-09), two sUSDai lines present. The indexer restarted on the new config and resumed live indexing from block 26155041, no errors. Steps 2 and 3 below use this seam literally.

Then merge and deploy the release. Steps 2 and 3 need its scripts, so they run right after the deploy finishes; the windows the live tick writes in between are already complete (above the seam), and step 3 rewrites them anyway.

2. Right after the release: fill each pool's swaps from creation up to the seam, one pool per run (the script is single-flight per name, and each run is one transaction):

bash
cd /opt/onchain-credit
scripts/run-cron.sh backfill-fluid-dex-swaps.ts \
  --pool 0xA2E3A4e2A08b5714FA974Ce88466D736BD8b39d9 --from 25268517 --to 26155040
tail -n 2 /tmp/onchain-credit-cron/onchain-credit-backfill-fluid-dex-swaps.log
scripts/run-cron.sh backfill-fluid-dex-swaps.ts \
  --pool 0xb9b87A1B79891A8C9251F501B1b5d71bC7c8aA24 --from 25268589 --to 26155040
tail -n 2 /tmp/onchain-credit-cron/onchain-credit-backfill-fluid-dex-swaps.log
#   each ends "DONE: <n> rows in [<created>, 26155040]; last back-filled swap at ..., first indexer
#   swap above the seam at ..." with no "fatal". The archive RPC must serve eth_getLogs over
#   9000-block spans (prod's Alchemy does; the public dRPC fallback refuses).

Check: one continuous history per pool, nothing duplicated across the seam.

bash
sudo -u postgres psql -d creddit -c "
  SELECT lower(contract_address) AS pool, count(*) AS swaps,
         count(DISTINCT (tx_hash, log_index)) AS distinct_logs,
         min(block_number) AS first_block, max(block_number) AS last_block,
         count(*) FILTER (WHERE block_number <= 26155040) AS backfilled
    FROM creddit_indexer_fluid_dex_pool.swap
   WHERE lower(contract_address) IN ('0xa2e3a4e2a08b5714fa974ce88466d736bd8b39d9',
                                     '0xb9b87a1b79891a8c9251f501b1b5d71bc7c8aa24')
   GROUP BY 1"
#   swaps = distinct_logs; first_block at or just after each pool's creation block.

3. Write the pools' 6h history (both pools in one walk, oldest first, through the current window; about 490 windows each, roughly half an hour):

bash
scripts/run-cron.sh backfill-fluid-dex-pools.ts \
  --pool 0xA2E3A4e2A08b5714FA974Ce88466D736BD8b39d9 \
  --pool 0xb9b87A1B79891A8C9251F501B1b5d71bC7c8aA24 \
  --from 2026-06-08
tail -n 2 /tmp/onchain-credit-cron/onchain-credit-backfill-fluid-dex-pools.log
#   "DONE - <n> rows written, 0 failed"; a non-zero failure count exits 1, re-run it (idempotent).

Check:

bash
sudo -u postgres psql -d creddit -c "
  SELECT pool_pair, count(*) AS windows, min(snapshot_ts), max(snapshot_ts),
         count(*) FILTER (WHERE fee_apy_usd IS NULL) AS unpriced,
         count(*) FILTER (WHERE token0_per_supply_share IS NULL) AS no_per_share,
         count(*) FILTER (WHERE swap_count = 0) AS no_swap_windows,
         round(avg(fee_apy_usd)::numeric * 100, 3) AS avg_fee_apy_pct
    FROM onchain_credit.fluid_dex_apy
   WHERE pool_address IN ('0xa2e3a4e2a08b5714fa974ce88466d736bd8b39d9',
                          '0xb9b87a1b79891a8c9251f501b1b5d71bc7c8aa24')
   GROUP BY 1"
#   min 2026-06-08 00:00, max the current window. unpriced = 27 per pool, all at or before
#   2026-06-14 12:00: sUSDai's first stored bar is 2026-06-14 13:00 UTC, and a registry token
#   with no bar is a BLANK by design (never vendor-quoted after the 2026-01-01 floor), so those
#   windows keep NULL dollar columns and fee APY; priced history starts 2026-06-14 18:00 and the
#   24h figure at 2026-06-15 12:00 (it needs three priced windows behind it). Do not "fix" them; filling sUSDai's first week of prices
#   would be its own decision (a price-bar backfill, then re-run this step). An unpriced window
#   AFTER 2026-06-14 12:00 is a real gap. no_per_share 0; no_swap_windows a minority. A run of
#   zero-swap windows across the seam means step 2 did not cover it: re-run step 2, then step 3.

4. List the vaults: the carry-listings runbook (list the 2026-10 carry batch, whose step 0 waits on this one). Run its steps for vaults 175, 176, 177 and 178 now: step 2's sync must report all four proposed (both pools snapshotted); step 3 fills their funding-rate history (the four pool-vault addresses it lists, --from 2026-06-08), which they lack because that series only follows proposed and active vaults; only then step 4's --approve fluid-vault-175 to fluid-vault-178.

5. Record the run here: the date in executed:, the seam block, step 2's row counts and step 3's check.

Rollback. None owed: every write is the pools' own rows. To undo, delete rows for THESE TWO POOLS ONLY (lower(contract_address) / pool_address IN the two addresses above; never an unfiltered delete on the shared indexer table) from creddit_indexer_fluid_dex_pool.swap at or below the seam and from onchain_credit.fluid_dex_apy; a vault that is not approved shows nowhere either way.

GATED STEP: list the 2026-10 carry batch (one supplying vault on Morpho; 24 new oracle cards) ​

  • belongs to: the carry listings PR (branch feat/carry-listings-2026-10), the release that ships it
  • executed: 2026-10-09
  • run record: (v0.85.0, release PR #1097, merge b520bbdb, deploy run 37970504638 green; the app restarted on 0.85.0 at 18:03:42Z; migrate.sh at 18:04Z applied 132 to 136, five files). Fred approved the card copy on 2026-10-09 (the copy sheet). Steps 1 and 2 are the first sync's run (18:40Z dry run, 18:41Z persist): all 24 PROPOSED, none in NEEDS A DECISION. Step 3 (18:42Z to 19:01Z): each of the 11 vaults 0 failed, 496 written for 160, 168 and 170, 495 for 171 to 173, 489 for 179 and 175 to 178 (the 1 to 7 absent windows predate each vault). Step 5 ran BEFORE step 4 (the promotion review's S2: with --market the scoped back-fill drops the approval filter, so the persisted proposed markets fill before they list): 18:43Z to 18:46Z, 361 snapshots … scoped to 13 market(s), done: ok=3616 failed=0 lostWindows=0. Step 4: the 13 Morpho keys at 18:48Z, the 11 Fluid keys at 19:01Z (all inside the 18:00 window of the back-fill), every one Set <key> -> active with its stored max LTV and liquidation threshold, no REFUSED: and no WARNING:. Step 6: refresh-vault-capacity.ts at 19:02Z, 31 Fluid and 18 Morpho carries, 62 ok / 0 failed; refresh-vault-risk.ts not needed. Step 7: deploy run 37970504638 re-run (attempt 2) 19:06Z to 19:07:33Z, green, Deployed b520bbdb at 2026-10-09T19:07:31Z, the static pages regenerated; on the box (curl localhost:3001) /carries serves all 24 keys and no fluid-vault-104, and /api/carry-history gives morpho-susde-pyusd-90ef0c5a a funding rate at 18:00 of 4.19% (1195 points) and morpho-susds-usdt-26b178d4 2.63% (295 points). Step 8 (19:09Z): exit 0, 24 [ok] lines, All 24 oracle cards assemble complete, verified and live.

What it changes for a user, in one line: /carries gains up to 24 carry trades (11 Fluid vaults, 13 Morpho markets), each with its oracle card, once Fred has approved the card copy (the copy sheet) and runs these steps.

Why a step at all. A release never lists a carry: a sync writes new carries as proposed, and each one lists only on an admin's --approve. Fluid's funding-rate history for a vault starts only when the vault is first proposed, and Morpho's market history starts only when the market is approved, so both are filled by hand around the approval. Prod only, never staging (staging reseeds nightly).

0. Prerequisite for Fluid vaults 175, 176, 177 and 178 (the sUSDai/USDC and sUSDai/USDT pool vaults): the sUSDai pools PR (#1091) must have shipped and its own runbook run first (the two DEX pools indexed, then its swap and DEX-fee backfills). Until then the sync keeps those four vaults blocked_pool; every step below runs for the other carries without waiting, and the same steps run for these four afterwards.

The whole batch's persist step (step 2) waits for PR #1095 on prod (the release that ends the one-market-per-pair rule). Under the rule before it, a persisting sync keeps only the deepest market of each collateral and loan pair. The second sUSDS -> USDT market (morpho-susds-usdt-26b178d4, about $46M borrowed, its card added after this step was first written) is now deeper than the listed one (morpho-susds-usdt-3274643d, about $11M), so a persist before #1095 would mark the listed market duplicate_market and drop that carry from /carries. Step 1's dry run writes nothing and can run any time. Once #1095 is on prod both markets are carries; the new one is in steps 4, 5 and 8 below.

1. Report (read-only). Run it directly so the report reaches the terminal; a direct run loads .env.local itself (without it the script stops on "DATABASE_URL not set"):

bash
cd /opt/onchain-credit
set -a; . ./.env.local; set +a   # DATABASE_URL and the RPC env, as run-cron.sh loads them
npx tsx scripts/sync-carries.ts --dry-run

Check: the carries below show under LISTED / PROPOSED as PROPOSED, none under NEEDS A DECISION with "oracle card incomplete". Each Morpho row prints its registry key (key morpho-…); the keys are listed below as well. wsrUSD -> USDC and PT-USDat-14JAN2027 -> USDC stay in NEEDS A DECISION by design (no card reader for their primary-and-backup oracle yet).

2. Persist the classification (writes the registries; nothing lists). Only once PR #1095 is on prod (see above):

bash
scripts/run-cron.sh sync-carries.ts

3. Fill each new Fluid vault's funding-rate history (one vault per run, oldest first, idempotent). The 6h refresher follows proposed vaults from step 2 on, but has no history before:

bash
for v in 0x9b3207736dbf0a04d292071b814821032152605a \
         0x56a25029b116a7aa329d5e6357e8679e824f6c83 \
         0x18aecd810742a6ae160f4c641fbbb14f15b7ed55 \
         0x009d7471fc3bd28fc45495d38978287fdf39416d \
         0x4aff5c338453d0ef0165900ca174cce3e9c46dff \
         0x1d3fadd621946c104d72bc2d01a79acdf9719eba \
         0xe6214008ab48e27c7289c7a8a9844ca49314d05c; do
  scripts/run-cron.sh refreshers/fluid-vault-rates.ts --backfill --vault "$v" --from 2026-06-08
done
# after step 0, the four pool vaults (175, 176, 177, 178):
#   0x26a5f44aac931f2abc1c89236a6dfde3ebeed997 0xc16f5c0996b80a4ae4f75652bbe684b6f6b808eb
#   0x0faa99e9662d5b6000f525b830ca2d054cdb8339 0x7e1874cdc9195163c23a1bb38b83e136b0b1d8e5

4. Approve each carry. --approve assembles its oracle card against the chain, prints it, and refuses the carry if the card is incomplete or any read fails; on success it flips the status and stores the max LTV and liquidation threshold. Run directly to see the card:

bash
cd /opt/onchain-credit
set -a; . ./.env.local; set +a   # DATABASE_URL and the RPC env, as run-cron.sh loads them
for k in fluid-vault-160 fluid-vault-168 fluid-vault-170 fluid-vault-171 fluid-vault-172 \
         fluid-vault-173 fluid-vault-179 \
         morpho-susde-pyusd-90ef0c5a morpho-pst-pyusd-b4977179 morpho-syrupusdc-pyusd-c9629945 \
         morpho-pst-usdc-002278ea morpho-pst-ausd-e90a6419 morpho-fxsave-usdc-17f7ae1b \
         morpho-stusds-usdc-d570c19c morpho-susdai-usdt-e6151adf morpho-susdai-ausd-69ab0544 \
         morpho-pt-usd3-17dec2026-usdc-f8c5aa31 morpho-pt-usdat-14jan2027-usdt-d8dd3e1d \
         morpho-pt-reusd-10dec2026-usdt-6acd1885 morpho-susds-usdt-26b178d4; do
  npx tsx scripts/sync-carries.ts --approve "$k"
done
# after step 0 and step 3 for them: fluid-vault-175 fluid-vault-176 fluid-vault-177 fluid-vault-178

A line starting REFUSED: names why; nothing was written for that key. A WARNING: that the liquidation threshold could not be read means step 6's risk refresh fills it.

5. Fill each approved Morpho market's rate history, straight after step 4 (the 6h refresher follows a market only from its approval on, so until this runs an approved Morpho carry has no funding history and its funding leg would read 0 or with the wrong sign):

bash
scripts/run-cron.sh backfill-morpho.ts --days 90 --market \
0x90ef0c5a0dc7c4de4ad4585002d44e9d411d212d2f6258e94948beecf8b4c0d5,\
0xb4977179610abfecfc8b76255a002c16b33f46d077beb86e5911e1fe9ee6e512,\
0xc9629945524f3fde56c7e8854a6c3d48e76b9d97236abbe73c750fcc7aeb8501,\
0x002278ea242ec722813b4fe3c8eeaa07dbc331c731cc0b4248a1bf0771f933ea,\
0xe90a6419afa96192cb088f63b779ddcb629a89f9126600d767d9442868087541,\
0x17f7ae1b52670010976b3fe41324cbb2b1eb7dd8f492e51764b2828371b86b84,\
0xd570c19c0dc0fbe4ab7faf4a37c4150e1c141c8aada8ca3e1b4b6c1b712af93d,\
0xe6151adff6709c6cea3276cfc940f54da76bc04199b0ec583d6a1a9d6410f5b0,\
0x69ab0544d77efb9b4fa8acc4f9cbfc18ddb1334acd9f46e5b10b893039b239b1,\
0xf8c5aa31ea6b2a068a9eddb46dd110cae57bf0f12be9583a3f9a818effecba89,\
0xd8dd3e1d051eee97d1353a113982afac90612c775f393edea45ef7f20caec489,\
0x6acd18854e43f93f5a90446004c35c72a68af1ad99f08cb247782ce6457914ca,\
0x26b178d49895f80ca3c39b2745efc4cd9adcddfcc73dae93e531e86977ec4d96

Drop any id whose --approve was refused in step 4. Collateral-exposure history for these markets is a separate unscoped run (data pipeline); the current exposure row arrives with the next 6h tick.

6. Refresh what does not ride the approval (processes A.5):

bash
scripts/run-cron.sh refresh-vault-capacity.ts   # Fluid Borrowable for the new vaults
scripts/run-cron.sh refresh-vault-risk.ts       # only if step 4 printed a WARNING

7. Re-prerender /carries (required). /carries is prerendered with an hour's revalidate window, so a render taken between step 4 and step 5 would keep serving a Morpho carry without its funding history for up to an hour. Re-run the latest successful "Deploy to production" run (it has no manual trigger; a re-run rebuilds and re-prerenders against the now-current database, deployment: ISR note and processes A.6). A prod deploy needs Fred's go:

bash
gh run rerun "$(gh run list --workflow deploy.yml --branch main --status success --limit 1 --json databaseId -q '.[0].databaseId')"

Open /carries after it finishes and check one new Morpho row shows a funding rate.

8. Check the cards as served (read-only; exits non-zero naming any card that fails):

bash
scripts/run-cron.sh check-oracle-cards.ts fluid-vault-160 fluid-vault-168 fluid-vault-170 \
  fluid-vault-171 fluid-vault-172 fluid-vault-173 fluid-vault-179 morpho-susde-pyusd-90ef0c5a \
  morpho-pst-pyusd-b4977179 morpho-syrupusdc-pyusd-c9629945 morpho-pst-usdc-002278ea \
  morpho-pst-ausd-e90a6419 morpho-fxsave-usdc-17f7ae1b morpho-stusds-usdc-d570c19c \
  morpho-susdai-usdt-e6151adf morpho-susdai-ausd-69ab0544 morpho-pt-usd3-17dec2026-usdc-f8c5aa31 \
  morpho-pt-usdat-14jan2027-usdt-d8dd3e1d morpho-pt-reusd-10dec2026-usdt-6acd1885 \
  morpho-susds-usdt-26b178d4

9. Record the run here: the date in executed:, and any key step 4 refused with its reason.

Rollback. scripts/run-cron.sh sync-carries.ts --reject <key> takes a carry off the page (or the direct run, with .env.local loaded as in step 1); the history rows the backfills wrote are idempotent and harmless.

Migration 134 (delisting proposals on the carry registry, additive) ​

  • belongs to: the delisting-by-consent PR (branch feat/delisting-by-consent), the release that ships it
  • executed: 2026-10-09
  • run record: (v0.85.0, release PR #1097, merge b520bbdb, deploy run 37970504638 green; the app restarted on 0.85.0 at 18:03:42Z; migrate.sh at 18:04Z applied 132 to 136, five files). 134 ran AFTER the deploy, in the release's one migrate.sh run (about 30 seconds after the app restart); the consequences listed below held for those seconds. The three columns present, all nullable: delist_proposed_at|timestamp with time zone|YES, delist_proposed_reason|text|YES, delist_proposed_status|text|YES.

Adds three nullable columns to carry_registry (delist_proposed_status, delist_proposed_reason, delist_proposed_at) and restates the table's grant to the app roles. No row is written. Additive, so staging auto-applies it. On prod it runs in the release's one scripts/ops/migrate.sh run, before or after the deploy (v0.85.0 ran it straight after). Either order is safe:

  • a persisting sync-carries.ts run (and --approve / --reject / --delist) refuses to start until the columns exist; a --dry-run works either way;
  • the 6h pendle-markets pass names the columns; on a database without them it logs "carry maturity/runway pass skipped" and leaves the status column alone (a matured carry is still hidden at read time, so no user sees a difference);
  • after a code rollback the previous release never names the columns, so they are inert.

Verify with \d onchain_credit.carry_registry (the three columns present, all nullable).

  • belongs to: the delisting-by-consent PR (branch feat/delisting-by-consent), the release that ships it
  • executed: 2026-10-09
  • run record: (v0.85.0, release PR #1097, merge b520bbdb, deploy run 37970504638 green; the app restarted on 0.85.0 at 18:03:42Z; migrate.sh at 18:04Z applied 132 to 136, five files). Step 1 at 18:40Z, after the sUSDai pools' step 3 (more than 15 minutes past the 18:00 boundary): DELISTING PROPOSED held exactly fluid-vault-17 (TVL $551), fluid-vault-18 ($5,461), fluid-vault-50 ($2,301), all below_floor, and fluid-vault-104 (gone: absent from Fluid API, $703k); morpho-susds-usdt-3274643d under LISTED; morpho-susds-usdt-26b178d4 PROPOSED. Step 2 at 18:41Z, exit 0, the same groups, persisted 120 Fluid + 92 Aave/Spark + 200 Morpho (27 listable) to the registries; 4 delisting proposal(s) recorded. Step 3: Delisted fluid-vault-104: active -> gone (absent from Fluid API), proposed since 2026-10-09. 1 carry_registry, 0 morpho_market_registry row(s) written.; 17, 18, 50 and 3274643d kept (Fred), the first three still active with their below_floor proposal standing. Step 4: the carry listings' step 7 re-run.

What it changes for a user, in one line: nothing on its own. From this release no sync removes a listed carry from /carries; it proposes the removal, and the carry stays until Fred removes it. The only automatic removal left is a PT that has matured.

Why a step at all. The first persisting sync after the release records a delisting proposal for every listed carry that fails a gate today (the old rule would have flipped some of them off the page; the 50% hysteresis band that kept others on is gone). Fred has decided these in advance (2026-10-09). After migration 134 is applied, on prod only:

1. Report (read-only), run directly so the report reaches the terminal:

bash
cd /opt/onchain-credit
set -a; . ./.env.local; set +a   # DATABASE_URL and the RPC env, as run-cron.sh loads them
npx tsx scripts/sync-carries.ts --dry-run

Check the DELISTING PROPOSED group. Expected today: Fluid #17, #18 and #50 (the small sUSDe vaults, below the $100k floor) and fluid-vault-104 (ezETH/ETH → wstETH, absent from Fluid's listing, proposed to gone). morpho-susds-usdt-3274643d is no longer demoted as a duplicate of the deeper sUSDS/USDT market, so it should NOT be proposed; if it is, the line says why. Anything else in the group is new since 2026-10-09 and goes back to Fred before step 3.

2. Persist (records the proposals; removes nothing):

bash
scripts/run-cron.sh sync-carries.ts

3. Apply Fred's standing decisions. KEEP fluid-vault-17, fluid-vault-18, fluid-vault-50 and morpho-susds-usdt-3274643d (do nothing: they stay listed, and keep showing under DELISTING PROPOSED on later runs while they fail). REMOVE fluid-vault-104:

bash
npx tsx scripts/sync-carries.ts --delist fluid-vault-104

It prints Delisted fluid-vault-104: active -> gone (absent from Fluid API), …. A REFUSED: line writes nothing and exits 2: if it says no delisting is proposed, step 2 did not run or the vault is back in Fluid's listing (ask Fred).

4. Re-prerender /carries so the removal shows before the hour's revalidate window ends: re-run the latest successful "Deploy to production" run (needs Fred's go), as in processes A.6.

The deeper sUSDS/USDT market (morpho-susds-usdt-26b178d4) is now judged on its own. Its oracle (Chainlink USDS/USD over a capped adapter around Chainlink USDT/USD) has its own approved card since #1096, so from the first persisting run it shows as PROPOSED, not under NEEDS A DECISION. No step here lists it: it lists with the batch, in the 2026-10 carry listings (steps 4, 5 and 8).

Migration 145 (asset profile records and the native supply series, additive) ​

  • belongs to: the asset profile redesign, step 1 (branch claude/gracious-planck-xmffk6), the release that ships it
  • executed: 2026-10-12
  • run record: (v0.87.0, release PR #1126, merge 1284e4c7 at 17:10:33Z on 2026-10-12, deploy run 38282474222 green 17:10:41Z to 17:11:55Z: app, ingester and worker restarted 17:11:53Z to 17:11:55Z, health 200, box on 0.87.0; 141 by hand at 17:10:13Z before the merge; one migrate.sh at 17:12:34Z to 17:12:41Z: 5 applied (140, 142, 143, 144 and #1124's 145), 144 total on disk; run as the combined pass.) The row check: 0x22ae3d9a738471f405169af055d31c687087d4c7|2026-10-12 (PST), and token_native_supply exists with its key (chain_id, token_address, snapshot_ts) and three checks. The crontab, backed up first to /var/tmp/v0870/crontab-backup-20261012T171303Z.txt (42 lines, neither job in it): the two lines of the asset profile jobs appended (prod only; staging untouched), each grep -c now 1. The hand run at 17:13Z: exit 0, [native-supply] PST: reader coingecko (CoinGecko's reported total supply for the solana contract) and [native-supply] 1/1 source(s) written; the row 360219644.338171, source coingecko, at 17:13:09Z. The review job's first run is the next Monday 04:55Z.

Creates asset_profiles (seeded with PST's record) and token_native_supply, and grants the app roles SELECT on the first and SELECT, INSERT on the second (the tables). Additive, so staging auto-applies it. On prod it runs in the release's one scripts/ops/migrate.sh run, before or after the deploy. Either order is safe:

  • before it, the release's profile loader answers from the shipped seed (the same record the migration inserts) and logs the failed read; the TVL tab reads no supply and says so; nothing a user sees is wrong;
  • after a code rollback the previous release never names either table, so they are inert.

Verify with SELECT address, reviewed_at FROM onchain_credit.asset_profiles (one row, PST, 2026-10-12) and \d onchain_credit.token_native_supply.

Then, on prod only, install the two crontab lines in the asset profile jobs and run the supply job once by hand so the TVL tab has its first reading the same day:

bash
cd /opt/onchain-credit && scripts/run-cron.sh refresh-native-supply.ts
grep -a 'native-supply' /tmp/onchain-credit-cron/onchain-credit-refresh-native-supply.log | tail -n 2

The log names the reader it used (coingecko, the decided source, unless SOLANA_RPC_URL is set in .env.local). The TVL tab appears only from the second day with a reading. Record the date here and that line.

Registry-selected hourly pool prices (migration 146) ​

  • belongs to: migration 146-hourly-price-feeds.sql, the release that ships registry-selected pool spot prices and daily feed reports
  • executed: 2026-10-13

Execution record (v0.89.0). Fred separately authorized production release and the historical replacement, then explicitly waived the remaining CI check. Release #1149 merged as 1eba7465; production deployment 38445617206 and release/tag 38445617288 succeeded. The desktop CI leg failed and reached its 50-minute limit; it was waived, not reported as passing. Unit, fixture, narrow-screen and zoom checks had passed, as had independent review.

Migrations 146/147 applied at 18:17 UTC. All four policies activated from the actual 18:00 UTC hour. Four read-only archive diagnostics returned accepted prices. A fresh backup, /opt/backups/creddit-2026-10-13T181807Z.dump, passed its integrity check at 18:21 UTC. Price writers were paused through replacement; the portfolio worker was stopped for execution and resumed afterward. The 00:00 UTC report line is installed once, credentials are configured, and the dry run passed. No unscheduled report was sent; the first scheduled delivery is not claimed here.

The final validated plan is archived privately on the server at /root/creddit-release-089/pool-history-final.json, checksum 435b5782265f26dae75404afe989c998e9a2a02c9da6f7c6554a723701670767. Both histories were replaced atomically through 2026-10-13 17:00 UTC:

AssetFirst UTC hourComplete hourly rowsCompleted repair audit
PST2026-05-30 04:003,27826640580-f1c2-432e-b7d8-b80f52cef173
sUSDai2026-06-17 23:002,8272fa66493-8d59-42ca-ac32-e151d385ecd4

Verification found no earlier rows, missing hours, rejected/carried prices or non-pool sources. Permanent registry floors are set. sUSDe's 9,429 and syrupUSDT's 10,393 existing market rows, and all four assets' yield/redemption histories, retained identical full-row checksums. Neither repair found a tracked portfolio consumer requiring re-derivation. PST's stored basis was recomputed and pre-cutoff basis removed.

sUSDai follow-up exception. The canonical repair command initially refused the basis step because sUSDai is deliberately outside BASIS_SERIES_TOKENS; production contained zero basis rows. Independently reviewed recovery took the same audit advisory lock and checked the exact audit/error, production owner connection, active market/pool registry state, zero unfiltered basis-universe membership and zero stored basis rows. It recorded the basis step as not applicable, with that evidence, and kept portfolio follow-up incomplete. Canonical finishRepair then completed portfolio checks and the audit at 19:28 UTC. No prices were replaced a second time. Do not generalize this to an asset with an expected or orphaned stored basis series; the original command still refuses that zero-membership case. Both audits are complete, so no resume is outstanding.

The procedure below is retained as the execution and rollback reference, not as a new authorization to repeat the historical replacement.

Migration and prospective feeds ​

Apply 146-hourly-price-feeds.sql through the migration ledger. It creates the decision timeline, repair audit, operational-health and report-delivery metadata, and expands the feed CHECK without changing any current assignment. The previous release remains compatible with that migration; token_price_bars remains the only price table.

After a successful code deployment, run scripts/ops/activate-hourly-price-feeds.sql as the registry owner in one transaction. Keep price writers stopped from deployment until activation and reload the registry consumers before resuming. Staging has no scheduled market-price writer; do not install one for this validation. The new code does not run the retired sUSDe ratio method, so do not leave production between deployment and activation with writers running. The activation selects Fluid PST/USDC and sUSDai/USDC, and Uniswap v4 sUSDe/USDT and syrupUSDT/USDT. The actual activation hour is their prospective boundary. PST has Dune as its sole backup; the other three have CoinGecko. Dune tape rows use CoinGecko alone; BTC.b/USDai have no backup. USD3 remains on its existing method until frxUSD has a supported USD reference. Neither migration nor activation deletes or replaces old market bars.

bash
# After successful staging deployment, as the registry owner:
sudo -u postgres psql -X -1 -v ON_ERROR_STOP=1 -d creddit_staging \
  -f scripts/ops/activate-hourly-price-feeds.sql

# Only at the separately authorized production release, after its deployment:
sudo -u postgres psql -X -1 -v ON_ERROR_STOP=1 -d creddit \
  -v expected_database=creddit -v allow_production=true \
  -f scripts/ops/activate-hourly-price-feeds.sql

Activation defaults to staging, checks the connected database and registry ownership, and serializes the cutover. A repeat preserves the existing decisions and permanent history floors. Verify all four pool assignments and open policy periods share the activation boundary, then reload the app registry and resume the authorized writers.

On staging, verify prospective spot bars are fresh and block-anchored, counter prices are accepted at the same hour, backups cannot publish before their grace, and the weekly review names the exact selected pool and discovery completeness. Existing sUSDe/syrupUSDT market history is preserved. Validate the affected /carries Collateral market to redemption basis chart, asset-profile market/basis histories and /portfolioValue and MTM PnL against the canonical bars. Do not run the historical repair.

At the separately authorized production release, install the daily report job using the server procedure. Confirm UTC scheduling, server-side alert credentials, a price-refresh completion checkpoint before delivery (or an explicit overdue-refresh report at the 00:30 deadline), successful delivery receipts for both reports and the absence of duplicate cron lines. The command's default mode is a dry run; --send is required for delivery. Do not substitute a Codex automation.

Explicit PST/sUSDai historical replacement, completed ​

This replaces all previous market-price bars for PST and sUSDai, including points before the replacement's first hour. It leaves no market points before:

AssetVerified pool creationFirst replacement UTC hour
PSTblock 25,133,683; timestamp 1,779,246,8512026-05-30 04:00
sUSDaiblock 25,268,517; timestamp 1,780,871,4472026-06-17 23:00

Read-only preparation checks verified the two first-hour samples, using archive pool state and the staging database's accepted non-carried USDC counter prices:

AssetSample blockSpot in USDCCounter USD priceResulting USD price
PST25,205,6601.1065833340.99999716666666641.106580199
sUSDai25,340,4181.0909636920.999789251.090733771

Both sampled blocks are one second before their hour. Their hashes are 0x0f0ed83be0324b0f0221df71edf9d82e5f860415f102edf3e65224e8ee9ee660 and 0x97cb38a0ab2411f97ab8561d5dc9405ceecf79c7cf2e477992932e31ac3c6878, respectively. These early states were collateral-only and extremely thin: approximately $68 and $74 of real reserves. The requested creation-plus-ten-days cutoff is retained despite that historical depth; today's reviewed depth is not a claim about those early hours. These checks made no database writes and verified only the first hour, not complete replacement-window coverage. The preparation command must still establish that coverage.

The first hour is ceilUTC(pool creation + 10 days). Every replacement price must be pool spot with a fresh same-hour counter conversion; no backup can fill its coverage. The command requires 100% of the completed hours in its window, so missing archive or counter evidence stops preparation without deleting anything. It never writes yield or redemption history. The original feed-decision periods remain unchanged; the repair audit records the retrospective reconstruction separately.

After explicit release authorization, take and verify the normal database backup. Drain and stop market-price writers and portfolio backfill/derivation work for the repair window, including already-running processes. This keeps the chosen end stable. Keep server secrets in the existing protected environment; the examples assume it is loaded. Choose an immutable, owner-readable plan-file path and a completed UTC end hour.

bash
# PREPARE only: database transactions are read-only; archive calls are reads.
# On production even preparation requires the explicit database guard flag.
node_modules/.bin/tsx scripts/ops/replace-pool-price-history.ts \
  --allow-production --plan-file=/var/tmp/pool-history-plan.json \
  --to=2026-10-13T00:00:00Z

# Review the exact plan, then execute it as the market-price table owner.
# Set DATABASE_URL for that owner connection without printing its value.
node_modules/.bin/tsx scripts/ops/replace-pool-price-history.ts \
  --execute --allow-production --confirm-db=creddit \
  --plan-file=/var/tmp/pool-history-plan.json

The shown end is an example: use the reviewed completed end at the actual release. The default allowed database is creddit_staging; production requires both the extra flag and exact database confirmation for execution. That guard is not authorization to run a staging repair in this task. Preparation writes a new plan file with wx and never overwrites an existing reviewed file. Execution is offline with respect to price sampling: it consumes the checksummed plan, verifies the current pool selection, stages both complete series in a temporary table, then locks the canonical table. If a market bar newer than the plan exists, prepare a new complete plan instead of discarding it.

One owner transaction stores counts, ranges, source totals and checksums in token_price_history_repairs, sets the permanent top-level historyFromHour, deletes only the two named assets' canonical market bars, and inserts their staged spot series. The audit stores no old or replacement price copies. Any failed row-count or quality check rolls back both assets. A database trigger prevents earlier prices from being reinserted even by a process with an old registry snapshot.

After that commit the command recomputes stored six-hour basis with the existing DB-only refresher, removes pre-cutoff basis, and queues affected portfolio consumers using the normal guarded re-derivation route. Daily market/basis metrics read the canonical series directly. The audit keeps separate follow-up progress. If follow-up fails, use the printed audit UUID; do not repeat the price deletion:

bash
node_modules/.bin/tsx scripts/ops/replace-pool-price-history.ts \
  --execute --allow-production --confirm-db=creddit --resume=<audit-UUID>

Repeat resume for each incomplete asset audit. Resolve any declined portfolio queue by its named reason, drain the queued derivations using the existing worker procedure, and verify their completion. An audit's complete state means basis replay and queueing finished; it does not claim that the worker already drained the queue. Check first/last hours, expected hourly counts, absence of earlier PST/sUSDai market rows, pool-only source tags and the permanent floors. Compare pre/post yield/redemption and sUSDe/syrupUSDT market-history checksums. Restart writers only after registry reload, and recheck that no pre-cutoff market rows can appear. Record audit IDs, counts, follow-up results and the release date in this section.

Rollback ​

Stop price writers before any code rollback. The preceding release cannot read active pool_spot assignments. Restore a compatible prior assignment from the captured policy timeline, including its feed-specific configuration and any constraint support needed for the legacy sUSDe ratio kind (migration 146 retains that CHECK vocabulary); do not replace sUSDe with the coarse Dune tape or clear a permanent history floor. Keep canonical bars and metadata; the audit contains no erased-price copies. A policy rollback is not a historical-price rollback: reverting replaced history requires its own reviewed owner operation using the verified pre-operation database backup. Resume only after code, constraints and the runtime registry agree.

Migration 147 (first LST asset-profile batch, additive) ​

  • belongs to: the first LST asset-profile content batch, the release that ships it
  • executed: 2026-10-13
  • run record: v0.89.0, release #1149; applied through the production migration ledger at 18:17 UTC. Verified PST reviewed 2026-10-12 and all five LST records reviewed 2026-10-13.

Adds profile records for wstETH, rETH, cbETH, wBETH and osETH with generated upserts. It does not change token-register terms, market readings or portfolio values. Staging applies it automatically through the additive migration runner. Production application belongs to a separately authorized release.

Verify six records in onchain_credit.asset_profiles: PST reviewed 2026-10-12, and the five LSTs reviewed 2026-10-13. Each LST expansion on /asset-profiles should use the same panel as PST. cbETH intentionally has no TVL tab under the existing supply rule. No new cron or home-network contract is needed.

Migration 148 (LST asset-profile copy rewrite, additive) ​

  • belongs to: the LST asset-profile copy rewrite, the release that ships it
  • executed: 2026-10-15
  • run record: v0.90.0, release #1155; applied through the production migration ledger at 14:11 UTC (migrate creddit: 1 applied), then the deploy re-run so /asset-profiles re-prerendered. Verified six records, review dates unchanged (PST 2026-10-12, the five LSTs 2026-10-13), the five new ledes and the simplified FIRST LOSS tags.

Rewrites the prose of the wstETH, rETH, cbETH, wBETH and osETH profile records (yield, loss and risks, liquidity) through generated upserts. Classification chips, tiles, references and review dates (2026-10-13) are unchanged, and so are token-register terms, market readings and portfolio values. Staging applies it automatically through the additive migration runner; production application belongs to a separately authorized release.

Verify six records in onchain_credit.asset_profiles with the same review dates as after 147, and that the wstETH record's first yield paragraph starts "wstETH is a share in Lido's pool of staked ETH, and the wrapped form of stETH". The section is titled Loss allocation waterfall and risks; PST, cbETH and wBETH show it as text with no band.

Migration 149 (LST asset-profile duration tags, additive) ​

  • belongs to: the asset-profiles table and chart fixes (PR #1158), the release that ships it
  • executed: 2026-10-16
  • run record: v0.92.0 (PR #1170); migrate.sh creddit applied 149-152 at ~18:22 UTC; 19 asset_profiles records, none reading "Open-ended staking"; deploy re-run for the re-prerender.

Rewrites the wstETH, rETH, cbETH, wBETH and osETH profile records through generated upserts: the Duration tags now say how long getting ETH back can take instead of "Open-ended staking", rETH and wBETH gain one Mint / redeem tag, wBETH's last liquidity sentence drops "(see the market basis to redemption chart below)", and the five review dates move to 2026-10-16. Prose otherwise, tiles, references, token-register terms, market readings and portfolio values are unchanged. Staging applies it automatically; production application belongs to a separately authorized release. Apply it, then re-run the deploy so /asset-profiles re-prerenders: until then prod's stored wBETH sentence points at a basis chart the new code no longer draws.

Verify six records in onchain_credit.asset_profiles; the five LSTs reviewed 2026-10-16, PST still 2026-10-12; no record's Underlying duration chip reads "Open-ended staking".

Migration 150 (weETH and ezETH asset profiles, additive) ​

  • belongs to: the weETH and ezETH asset profiles (PR #1159), the release that ships it
  • executed: 2026-10-16
  • run record: v0.92.0 (PR #1170); migrate.sh creddit applied 149-152 at ~18:22 UTC; 19 asset_profiles records, none reading "Open-ended staking"; deploy re-run for the re-prerender.

Adds the weETH and ezETH profile records through generated upserts (review date 2026-10-16), so both rows open on the new profile layout instead of their old write-up. Token-register terms, market readings and portfolio values are unchanged. Staging applies it automatically; production application belongs to a separately authorized release. Apply it after 149, then re-run the deploy so /asset-profiles re-prerenders.

Verify eight records in onchain_credit.asset_profiles, and that ezETH's first liquidity paragraph says the queue waits a cooldown of fourteen days.

Migration 151 (savings-token asset profiles, additive) ​

  • belongs to: the sUSDS, sGHO, sUSDf, wsrUSD and fxSAVE asset profiles, the release that ships it
  • executed: 2026-10-16
  • run record: v0.92.0 (PR #1170); migrate.sh creddit applied 149-152 at ~18:22 UTC; 19 asset_profiles records, none reading "Open-ended staking"; deploy re-run for the re-prerender.

Adds five profile records through generated upserts (review date 2026-10-16), so those rows open on the new profile layout instead of their old write-up. All five are priced at redemption, so their pages draw no Market basis to redemption chart. Token-register terms, market readings and portfolio values are unchanged. Staging applies it automatically; production application belongs to a separately authorized release. Apply it after 150, then re-run the deploy so /asset-profiles re-prerenders.

Verify thirteen records in onchain_credit.asset_profiles.

Migration 158 (retained transaction receipts for entries read from the fill, additive) ​

  • belongs to: 158-portfolio-fill-inputs.sql and the #1221 entry-basis change (PR #1229, part of programme PR #1224), the release that ships them
  • mandatory: the release that ships migration 158 applies it before the ledger worker restarts on the new code; its separately authorized production release then validates the selected test wallets by re-deriving them
  • executed: 2026-10-21
  • run record: v0.97.0, release PR #1239, deploy commit d2487c71. migrate.sh applied 156, 157 and 158 in order at 19:58:01Z on 2026-10-21 while the ingester and ledger worker were stopped; the app restarted on the new code at 20:00:29Z and the ingester and worker at 20:00:53Z. Verified 2026-10-22: onchain_credit.portfolio_fill_inputs exists with SELECT and INSERT for onchain_credit (and onchain_credit_staging). Per the owner's waiver below, no wallet was re-derived; all production accounts were then deleted at the owner's request (2026-10-22 account deletions).

Creates onchain_credit.portfolio_fill_inputs (receipt, transaction, call trace and pinned Lido totals per chain and transaction hash, insert-only) with SELECT and INSERT for the application roles. Staging applies it automatically before the staging app restart; staging has no long-lived ledger worker. For a separately authorized production release, apply it with migrate.sh after 157-morpho-market-primitive.sql, then restart the ledger worker. Verify the table and its grants. From then on the derivation fetches the receipt of each transaction holding a matched trade or a venue movement once (one eth_getTransactionReceipt, plus eth_getTransactionByHash and trace_transaction where native ether or Lido shares move, plus three pinned Lido reads where stETH moves) on the archive RPC, and keeps it. Rows stored before the release keep their estimated entries: reading those from their fills needs a re-derive. After the separately authorized production release, re-derive only the explicitly selected test wallets as a mandatory validation step: record their addresses and elapsed first-build time, then check the proved fill prices, estimated fallbacks and Activity. Do not re-derive other wallets or run a staging backfill as part of this shipment. This entry does not authorize production operations; the production release requires Fred's separate go. Newly observed rate facts retain an optional exact raw ratio in their existing JSON; this needs no additional schema migration. Historical rows without that ratio retain their legacy decimal evidence boundary and are not silently refreshed from an archive at page load. Existing authorized rate-fact repair and coverage-restatement runs retain raw getter ratios too; custom numeric-only readers retain only their supplied precision. A changed retained fact invalidates the served-value cache, even if its numeric rate is unchanged. This adds no automatic historical repair or release step.

v0.97.0 validation scope (owner decision, 2026-10-21). The owner waived entry-price re-derivation of all existing accounts and wallets: they are test data intended for later deletion. This release applies and verifies migration 158 but does not queue historical entry-price repairs or delete those accounts. The local and release-CI fixture/browser gates validate the entry behavior. Other required asset, market-history and coverage operations remain in scope.

Shipment scope (#1219 + #1221, then #1222 and #1220). Unknown entries and dates show explained dashes; proved trades supply exact entry prices and basis, with hourly-price estimates flagged. #1220 (the pre-window entry lookup, migration 159) gives a holding opened before the window its real At entry, Dislocation PnL and Held since wherever the wallet's own receipts explain it exactly; one bought by a plain transfer in or further back than the lookup reads keeps the dash, and so does one supplied at a venue before the window (Fred, 2026-10-22: the lookup covers holdings held bare in the wallet). #1222 treats a PT and its underlying as one claim, so a PT's entry is carried into its payout token (M32).

The final review correction preserves an available estimated debt entry pair when venue-booked units cannot be proved. At entry basis, Dislocation PnL and Lifetime PnL remain available, while both entry prices stay unavailable. Unknown historical entries and unproved collateral allocations remain withheld. This correction changes no movement accounting or operational release step.

Migration 158 is the undeployed receipt migration formerly numbered 156, then 157, in historical review evidence. Staging's already-landed 156-tori-strusd.sql and 157-morpho-market-primitive.sql keep their names and contents.

Migration 159 (pre-window entry receipts and their verdicts, additive) ​

  • belongs to: 159-prewindow-entry-receipts.sql and the #1220 pre-window entry lookup, the release that ships them
  • mandatory: the release that ships migration 159 applies it before the app restarts on the new code (the writer and the loader both tolerate its absence, so applying it after the deploy only delays the found entries)
  • executed: pending

Creates onchain_credit.portfolio_prewindow_entry_receipts and onchain_credit.portfolio_prewindow_entry_legs (FK wallet -> accounts(uid) ON DELETE CASCADE, lower-case wallet CHECKs) with SELECT, INSERT, UPDATE and DELETE for whichever application roles exist. Staging applies it automatically. For a separately authorized production release, apply it with migrate.sh after 158-portfolio-fill-inputs.sql, then verify both tables and their grants (\dp onchain_credit.portfolio_prewindow_entry_*). No backfill runs as part of this step: each wallet's next build walks its pre-window holdings (the runbook's pre-window entry lookup states the caps, the cost and the line to read). The first staging builds after the deploy are the measurement: record the elapsed time and archive calls their lines print here, as the run record.

Migration 152 (credit and yield asset profiles, additive) ​

  • belongs to: the sUSDe, syrupUSDC, syrupUSDT, reUSD, sUSDai and USD3 asset profiles, the release that ships it
  • executed: 2026-10-16
  • run record: v0.92.0 (PR #1170); migrate.sh creddit applied 149-152 at ~18:22 UTC; 19 asset_profiles records, none reading "Open-ended staking"; deploy re-run for the re-prerender.

Adds six profile records through generated upserts (review date 2026-10-16). With these every listed asset opens on the new profile layout; the old write-up remains only as the fallback for a profile that cannot be assembled. Token-register terms, market readings and portfolio values are unchanged. Staging applies it automatically; production application belongs to a separately authorized release. Apply it after 151, then re-run the deploy so /asset-profiles re-prerenders.

Verify nineteen records in onchain_credit.asset_profiles.

Repo lending: the USDtb tab (Aave v3 and Fluid): post-deploy steps, in order ​

  • belongs to: the USDtb deposit tab on Repo lending (branch feat/usdtb-repo-lending), the release that ships it; no migration
  • executed: 2026-10-16
  • run record: v0.92.0 (PR #1170). Step 1: Aave 2,052 rows (2025-05-21 to 2026-10-16 18:00, latest $12.68M deposited), Fluid 1,992 rows (2025-06-05 to 2026-10-16 18:00, latest $1.59M supplied). Step 3 run ~18:25 UTC: Fluid USDtb book $1.5M, 5 slices, 100% coverage; Aave v3 USDtb book $7.84M, 199 borrowers, 14 slices; no SparkLend/USDtb discovery error. Step 4 deploy re-run; /repo-lending lists USDtb. Step 2 run 2026-10-16 ~19:11 UTC on Fred's go: 2,056/2,056 windows ok, 0 failed, 0 before listing; USDtb Aave rows 2,052 before, 2,057 after (2025-05-21 00:00 to 2026-10-17 00:00, 0 without a supply index).

What it changes for a user, in one line: Repo lending gains a USDtb tab between RLUSD and GHO whose Pooled view lists Aave v3 and Fluid, each with its collateral breakdown; its Isolated view is empty (no Morpho market lending USDtb clears the listing bar: the largest, sUSDe collateral, had $0.9M borrowed on 2026-10-16). On /portfolio, a Repo lending row supplying USDtb on Aave or holding fUSDtb now shows its market's collateral and utilization and links to the row.

On-chain census behind it (2026-10-16, block ~26,204,800): Aave v3 Core USDtb reserve ~12.68M deposited, ~7.85M variable debt, supply rate ~1.5%, borrowable, LTV 0 (not collateral), reserve factor 20%, kinked curve at 80%; Fluid Liquidity Layer ~1.59M supplied, ~1.47M borrowed (92% utilization), supply rate ~4.9%; SparkLend lists no USDtb reserve.

  1. Deploy. Nothing is migrated. Fluid's USDtb rows already exist (the Liquidity Layer refresher writes every token it lists), so the Fluid row can appear on the first render. The Aave row appears with the first 6h refresh-assets.ts tick that reads USDtb as a curated reserve (it was read before only while an approved carry borrowed it, so older rows may exist with gaps). Check both books:

    bash
    psql "$DATABASE_URL" -c "SELECT 'aave' v, count(*), min(snapshot_ts), max(snapshot_ts), max(total_deposited) FROM onchain_credit.aave_v3_reserve_apy WHERE token_address = '0xc139190f447e929f090edeb554d95abb8b18ac1c'
      UNION ALL SELECT 'fluid', count(*), min(snapshot_ts), max(snapshot_ts), max(total_supply / 1e18) FROM onchain_credit.fluid_ll_apy WHERE token_address = '0xc139190f447e929f090edeb554d95abb8b18ac1c'"

    Sizes read in dollars (~12.7M Aave, ~1.6M Fluid on 2026-10-16), never ~1e12 times that.

  2. USDtb Aave rate history (owner's go; archive-RPC heavy, resumable with --from). Aave only: SparkLend has no USDtb reserve and the script attempts an asset only where it is listed. Windows before the reserve was listed are skipped, not written. Fluid needs no walk. Also moves /carries: the approved Aave sUSDe/USDtb carry reads its borrow cost from these same rows, so filling the gaps can shift that carry's history. Count the rows before and after so any change traces to this step.

    bash
    psql "$DATABASE_URL" -c "SELECT count(*), min(snapshot_ts) FROM onchain_credit.aave_v3_reserve_apy WHERE token_address = '0xc139190f447e929f090edeb554d95abb8b18ac1c'"   # before
    scripts/run-cron.sh backfill-repo-reserves.ts --assets USDtb
    psql "$DATABASE_URL" -c "SELECT count(*), min(snapshot_ts) FROM onchain_credit.aave_v3_reserve_apy WHERE token_address = '0xc139190f447e929f090edeb554d95abb8b18ac1c'"   # after
  3. Collateral breakdowns (owner's go). The 6h crons do this by themselves; running them by hand fills the two panels now:

    bash
    scripts/run-cron.sh refresh-collateral-exposure.ts   # Fluid USDtb
    scripts/run-cron.sh refresh-lending-positions.ts     # Aave USDtb

    The first lending-positions run scans the USDtb variable-debt token's log history from the reserve's listing (chunked; later runs scan only from the stored cursor). Neither run should log a SparkLend/USDtb "reserve missing from discovery" error: the absence is declared.

  4. Re-run the deploy (or wait for the 30-minute regeneration) so /repo-lending prerenders with both rows, and check the USDtb tab: Aave v3 and Fluid under Pooled, nothing under Isolated.

  5. Optional, report-only: scripts/run-cron.sh repo-isolated-check.ts now scans USDtb-loan Morpho markets too; expect none qualifying and nothing to approve.

  6. Record executed: with the date and step 1's counts.

Staging runs no refreshers and reseeds nightly, and gets no backfill: the tab shows there only for whatever USDtb rows the reseeded database already carries.

GATED STEP: ingest Pendle limit-order fills from the floor, and re-derive their makers ​

  • belongs to: the release that ships Pendle limit-order fills on principal tokens (PR #1210, branch feat/pendle-limit-order-fills; no migration)
  • mandatory: the release that ships it runs steps 1 to 5 before it is declared done: until step 1 runs, every limit-order fill before the deploy is missing from the stored history, and a wallet that bought or sold a principal token by limit order keeps the wrong holding and the refused rebuild described below; node scripts/ci/release-steps-due.mjs and the release PR's check summary list it while it is owed
  • executed: 2026-10-20

What it changes for a user, in one line: a wallet that buys or sells a principal token through a Pendle limit order (it signed the order, somebody else filled it) shows each fill on Activity as "Bought PT-…" (or "Sold PT-…") with the payment under it, and its principal-token holding on Positions counts the tokens it bought; before, the tokens never arrived on the books and the payment read as money withdrawn.

What ships. Code only. The pendle-router stream gains a second filter (Pendle's limit-order contract 0x000000000000c9b3e2c3ec88b1b4c0cd853f4321, its OrderFilledV2 event alone), the Pendle derivation books each fill on the maker's principal-token holding at the price it paid (data-pipeline, "A limit order somebody else filled"), the limit-order contract joins Pendle's venue addresses so the maker's payment is a movement to a venue, the reading audit's Pendle evidence asks for the same fills, the pre-window lookup (a held PT's purchases from before the wallet's window) counts them as the wallet's real fills, and the stream's --verify gains a seventh anchor (at least one fill on the contract over the verified range). From the deploy the live ingester stores every new fill; nothing below the live cursor is stored until step 1.

Between the deploy and step 1 nothing gets worse. The stream's certificate is the singleton '*' row, so no wallet withholds; a fill before the deploy is simply still missing, exactly as before the release, and a fill after it books correctly. Run steps 1 to 3 straight after the deploy.

The wallet that found it, measured 2026-10-19. 0x3dab3d64af2ce47b3609739969dbfd8e93ce1d91 bought 151,691.100113 PT-reUSD-10DEC2026 in 11 limit-order fills (blocks 26,024,830 to 26,143,547) and supplied 295,000 PT to Morpho; unbooked, its holding re-derived from its window start ran to −50,784.5 PT at block 26,173,571 and derive jobs #3764 (audit), #3769 (continuous) and #3814 (sweep) parked failed, paging "ledger-derive-lag" hourly. At 19:55Z the same day a full user wipe ran (0 accounts, 0 flow rows, every derive job gone; raw_events kept), so those three jobs no longer exist and this wallet is not enrolled: there is nothing of it to requeue or re-derive. Step 4 lists whoever is enrolled at release time, and a wallet added after step 1 is derived correctly by its own registration replay.

Prod, in order. Steps 1, 2 and 4 write prod and need the owner's go; steps 0, 3 and 5 are read-only.

  1. Before step 1, read-only: the band's baseline, the router rows already stored over the band's range (218,743 on 2026-10-19), which step 2 checks against:

    sql
    SELECT count(*) FROM onchain_credit.raw_events
     WHERE chain_id = 1 AND stream = 'pendle-router' AND block_number BETWEEN 24136053 AND 25833248;
  2. GATED: sweep the stream from the floor to its live cursor, so the new filter's history is ingested (attended; idempotent upserts, archive RPC; the router's own logs are re-read and change nothing):

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    TO=$(psql "$DATABASE_URL" -tAc "SELECT last_scanned_block FROM onchain_credit.chain_scan_cursors WHERE chain_id = 1 AND scope = 'ledger:pendle-router'")
    npx tsx scripts/backfill-event-ledger.ts --stream pendle-router --from 24136053 --to "$TO" --window 5000 --dry-run
    npx tsx scripts/backfill-event-ledger.ts --stream pendle-router --from 24136053 --to "$TO" --window 5000

    What it costs. About 2.1M blocks at a 5,000-block window, ~420 eth_getLogs windows of two filters each against the archive endpoint; the router's whole stream is ~130 logs per 1,000 blocks over this range (218,743 stored from the floor to block 25,833,248) and is re-read, not re-written, and the new rows are the fills: 50,616 OrderFilledV2 logs from 24,136,053 to 26,228,894 (40,226 of them at or below 25,833,248), measured 2026-10-19 in 50,000-block windows, none of the earlier OrderFilled event. Expect raw_events to grow by about 50,000 rows (a few tens of MB) and a run of roughly an hour. An explicit range is a repair, not a completion: it prints not a completion run; the rollout marker was not evaluated and exits zero.

    Check, read-only:

    sql
    SELECT count(*), min(block_number), max(block_number) FROM onchain_credit.raw_events
     WHERE chain_id = 1 AND stream = 'pendle-router' AND address = '0x000000000000c9b3e2c3ec88b1b4c0cd853f4321'
       AND topic0 = '0x338aa396bce529256f46f1d51f463cc5be80195004e47cf0a1527507d3840447';

    About 50,616 plus the fills since 2026-10-19, the first near block 24,136,053.

  3. GATED: re-measure the stream's history band, from the second provider, because condition 1 judges the stored rows over [24,136,053, 25,833,248] and that range now holds the fills too (the band on record is 671,654 router logs from 22,527,558, measured before the filter existed):

    bash
    cd /opt/onchain-credit && set -a; . ./.env.local; set +a
    LEDGER_VERIFY_RPC_URL=<second provider> \
      npx tsx scripts/record-ledger-backfill-band.ts --stream pendle-router --to 25833248 \
        --note "<date> the limit-order contract's fills join the pendle-router stream" --window 5000 --dry-run
    # then the same with --confirm in place of --dry-run

    Expect step 0's count (218,743 on 2026-10-19) plus 40,226 fills.

  4. The verdict (read-only):

    bash
    npx tsx scripts/backfill-event-ledger.ts --verify --stream pendle-router

    verify PASS, condition 4 naming seven anchors (the six router events and the limit-order fill). Any condition missing: stop.

  5. GATED: after step 3, list the enrolled makers (read-only), then re-derive each from its floor with the runbook's rederive insert, and read each done from portfolio_derive_jobs:

    sql
    -- read-only: every enrolled wallet that made a limit order a stored fill names (maker = data word 5)
    SELECT DISTINCT a.uid
      FROM onchain_credit.accounts a
      JOIN onchain_credit.raw_events e
        ON e.chain_id = 1 AND e.stream = 'pendle-router'
       AND e.address = '0x000000000000c9b3e2c3ec88b1b4c0cd853f4321'
       AND e.topic0 = '0x338aa396bce529256f46f1d51f463cc5be80195004e47cf0a1527507d3840447'
       AND substr(e.data, 347, 40) = substr(a.uid, 3)
     ORDER BY 1;

    Zero rows means nothing to re-derive (the expected answer after the 2026-10-19 wipe, unless a maker enrolled since). A wallet added later needs no step: its registration replay derives its whole window from its history floor, and after step 1 every fill inside that window is stored and books as a purchase or sale like any router fill. A fill before the window is part of the holding the window opens with, and the same build's pre-window lookup now counts it among the wallet's real fills (from 2026-01-01, the floor step 1 sweeps from), so that holding opens on its real lots and locked-in rate rather than the stand-in.

  6. Check, read-only, per re-derived wallet: its principal-token fills, and that no holding of it is negative:

    sql
    SELECT block_number, log_index, position_key, kind, amount_raw, consideration_raw, to_balance,
           meta->>'orderType' AS order_type, meta->>'ptTransfer' AS pt_transfer
      FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND wallet = '<wallet>' AND meta->>'route' = 'limit-order'
     ORDER BY block_number, log_index;
    SELECT position_key, block_number, to_balance FROM onchain_credit.portfolio_flow_events_v2
     WHERE chain_id = 1 AND wallet = '<wallet>' AND to_balance < 0;

    One deposit per buy and one withdraw per sell, each consideration_raw the fill's own payment, and the second query empty. The payment beside each buy is a transfer_out on the payment token's wallet:token: holding with counterparty_class = 'venue'.

Execution record (2026-10-20, v0.96.0) ​

The owner explicitly approved production deployment and the required operations, and waived the full release CI for this release. Release PR #1223 merged at b9c179af206dc19f406600cb5f311e0955969f2d. The staging deployment and smoke passed on the version bump (34 passed, 14 expected skips); the constituent feature checks were green. The full release CI was cancelled under that explicit waiver, without changing workflow configuration. The production deploy passed, the running checkout and version were verified, the origin app/database health check passed, and the restarted ingester completed a cycle. The v0.96.0 release was published, and staging was fast-forwarded to the merge commit.

The preflight found 218,743 router rows over [24,136,053, 25,833,248]. The archive endpoint and historical sweep receipts were eth-mainnet.g.alchemy.com; the independent verification endpoint was gateway.tenderly.co, exported throughout the measurement and verification.

Step 1 ran with its dry run first, then swept [24,136,053, 26,233,300] in 5,000-block windows and added 50,753 rows. The immediate count was 50,761 limit-order fills (including live ingestion), from block 24,136,144 to 26,233,393. The history-band count became 258,969: the original 218,743 plus 40,226 fills.

Step 2's dry run and confirmed measurement each independently counted 258,969 claimed and raw logs over 680 chunks and two declared addresses. The confirmed run recorded that band over [24,136,053, 25,833,248], replacing the older pre-filter band. Step 3 passed at 11:15:23 UTC, verification run 65944ab7efb3:

  • Exact row count: 258,969, with no out-of-scope stored rows.
  • Receipt continuity: 1,431 receipts, no gap.
  • Independent digest: matched over [25,456,053, 25,461,052].
  • Named anchors and certificate: all seven anchors present; singleton certificate valid.

Step 4 found zero enrolled limit-order makers, so no Pendle maker required re-derivation and step 5's maker-specific checks had no rows to inspect. Five wallets had enrolled since the previous release's account wipe (two completed builds and three empty builds). To apply the cross-view Swap writer change from PR #1209 to that existing population too, jobs 4046–4050 were queued only after verification, from each wallet's floor 26,014,998 through requested head 26,233,434.

All five rebuilds finished done on their first attempt, the last at 11:17:38 UTC; each derived through the ingested tip available to it. Job 4049 rewrote two rows as one cross-view swap group: one internal_out, one internal_in, neither carrying a consideration. The other builds needed no rewritten rows. Follow-up audit jobs 4051 and 4052 each checked 33 readings and finished done, with no openings or adjustments booked. The final queries found no negative holding balances across the five wallets and no maker-specific limit-order rows, consistent with the empty enrolled-maker set. The origin app/database health check remained healthy at 11:17:57 UTC.

Flash-loan carry opens: re-derive the wallets whose open is now proven ​

  • belongs to: PR #1251, the release that ships it
  • executed: pending

The atomic-carry proof now reads three more exchange families (Uniswap V4 hookless pools, EulerSwap pools, Fluid DEX pools), so a flash-loan open whose sale went through one of them is proven, and Activity lists its steps (Supplied equity, Borrowed with flash loan, the exchange, Supplied, Borrowed, Paid back flash loan) with the equity as the line's amount. That evidence is written into the movements when a wallet is derived, so a transaction derived before the release keeps reading as plain movements until its wallet is re-derived. The receipts are already retained (migration 158): a re-derive makes no new archive reads for them. New wording on transactions that were already proven needs nothing.

After the release is on prod, and only with Fred's go, list the wallets with a Fluid borrow or repayment in a transaction whose retained receipt carries a Balancer flash loan and whose movement states none (read-only):

sql
SELECT DISTINCT f.wallet, f.tx_hash
  FROM onchain_credit.portfolio_flow_events_v2 f
  JOIN onchain_credit.portfolio_fill_inputs i
    ON i.chain_id = f.chain_id AND i.tx_hash = f.tx_hash AND i.component = 'receipt'
 WHERE f.venue = 'fluid' AND f.kind IN ('borrow', 'repay') AND NOT (f.meta ? 'executionFlash')
   AND i.payload::text LIKE '%0x0d7d75e01ab95780d3cd1c8ec0dd6c2ce19e3a20427eec8bf53283b6fb8e95f0%';

On 2026-10-22 it named one: 0x4adfcdb13a9f3a7f3f2ffdf300441e42358b58c9, transaction 0x39a3c603…2f86. Enqueue a whole-window rederive for each wallet it names with the ledger-first release's INSERT (step 7), wait for done, and re-run the query: a wallet it still names holds a shape the proof does not cover (another lender, a fee, a hooked pool), which stays plain movements by design. Then open Activity for the wallet and check the line reads Opened carry trade at −5.2263 weETH with the six steps. A re-derive can also read an entry price from the fill wherever a wallet's route went through the three new exchange families, which moves that holding's At entry from an estimate to the traded price.

syrupUSDT pool-only historical replacement ​

  • executed: 2026-10-14
  • scope: Ethereum syrupUSDT 0x356b8d89c1e1239cbbb9de4815c39a1474d5ba7d only.
  • authorization: replace its full market-price history with the selected pool and remove history before October 30, 2025; preserve yield/redemption facts and other assets.
  • pool: Uniswap v4 0xd861038a98942312d1495dd1313fb66c7e7de48f549a15edf3a45decf7338e1d, syrupUSDT/USDT, fee 800, tick spacing 5, no hooks. Initialize transaction 0x471d7f8939f1a1bd1c4f4da1fb20d4950de7d373d54b5f25b68371e6343600f1, block 23691893, timestamp 1761847751 (2025-10-30 18:09:11 UTC). The approved first sample is 2025-10-30 19:00 UTC; no ten-day delay applies.
  • liquidity review: 66 archive samples from creation onward had LP principal worth at least 4.19 million USDT; the first sample was 9.92 million USDT. This is sampled evidence, not a claim that this pool was the deepest at every historical hour. The preparation additionally validates active liquidity and complete fresh USDT/USD conversion for every replacement hour before applying anything.

Prepare with scripts/ops/replace-pool-price-history.ts --asset=syrupUSDT --plan-file=... against the intended database (production additionally needs --allow-production). Review the complete plan and checksum, take and verify a fresh backup, drain price writers and affected portfolio derivations, and execute the exact plan as owner with --execute --confirm-db=... --allow-production. The original feed-decision timeline remains intact; the historical-repair audit describes the changed period. The registry gets the creation facts and permanent historyFromHour; its current selection activation and single CoinGecko backup remain intact. Resume interrupted basis/wallet follow-up by audit ID, not by repeating deletion.

Verify zero syrupUSDT market bars before the floor, complete hourly pool coverage after it, no carried/rejected replacement bars, regenerated basis and affected portfolios, and unchanged other-asset prices and yield/redemption facts. Restore the drained jobs and refresh served data. Record actual execution evidence here after completion.

Execution record (2026-10-14) ​

  • belongs to: v0.89.0 syrupUSDT historical repair, PR #1151
  • executed: 2026-10-14

Repair tooling merged through PR #1151 (d300a8bd, reviewed head 250fe2ee), with both CI passes green after the canonical-address fix and independent review converged. Staging deploy 38594213036 succeeded. No production application release was made; production remained on v0.89.0 (1eba7465) and the reviewed owner tool ran in an isolated operations directory against that release's existing data helpers.

  • Every one of the 8,368 production hourly observations was read at its exact at-or-before archive block, with a fresh same-hour USDT/USD conversion. All hourly active-liquidity values matched replayed pool liquidity events. The minimum reconstructed LP principal was $4,195,430.31, exceeding the $1m selection threshold throughout the replacement grid. This is pool principal, excluding uncollected fees.
  • Fresh backup /opt/backups/creddit-2026-10-14T154741Z.dump (2.0 GiB) was verified by a full pg_restore --file=/dev/null decode at 15:52 UTC. The wrapper's first integrity check could not read the root-private file as postgres; root's subsequent full decode succeeded. No database restore was performed.
  • Staging installed 8,356 hourly bars through 2026-10-13 22:00 UTC under repair baa149ca-098e-43c4-bb17-65fd201b0791; its scoped backup is /root/creddit-syrup-repair/staging-before.dump.
  • Production atomically replaced 10,410 previous market bars at 16:00:59 UTC with 8,368 pool bars from 2025-10-30 19:00 UTC through 2026-10-14 10:00 UTC. Repair 00336d4e-4d46-4eb7-ad47-577b5fff5c92 completed basis/queue follow-up at 16:01:02 UTC. Plan checksum: 10667761009dc1c8d8f17a0d88ec73fdf7c86a86caf6123e5863be11d09caf05.
  • Both databases have zero pre-floor market bars, zero pre-floor basis rows, complete hourly replacement coverage and zero carried/rejected/non-pool replacement rows. The registry stores creation timestamp/block and historyFromHour=1761850800. Current activation 1791914400, the selected pool and the single CoinGecko backup are preserved. Existing feed-decision periods are unchanged; the repair audit records the historical substitution.
  • Before/after checksums match for all other assets' market bars, all yield/redemption rows, other assets' basis, other registry rows and all feed-decision periods, on both staging and production. Production re-derived its one affected portfolio: job 2763 finished done at 16:02:40 UTC, without error. No stored portfolio depended on removed pre-floor prices. Staging had no affected portfolio.
  • The 23 production refresh cron entries were restored byte-for-byte, and the ledger worker resumed. The application and worker are online; production health returned HTTP 200. Both environments' actual Trade Analytics responses contain no market/basis values before the floor. That chart uses a six-hour display grid, whose first non-null point is October 31 00:00 UTC; the underlying hourly table starts October 30 19:00 UTC.

Plans, verification output, backup verification and preparation evidence are retained under /root/creddit-syrup-repair/. The original pool-feed decision timeline and yield/ redemption facts remain intact. Normal future feed collection continues from the existing pool selection with CoinGecko as its only backup.

Migration 153: account activity ​

executed: 2026-10-18

Production activation completed with explicit release authorization on 2026-10-18. All timestamps below are UTC. The earlier staging work did not perform production operations.

Staging completed 2026-10-18: PR #1183, squash commit 15bdac3d, deployed successfully in run 39109514199, including its Playwright staging smoke. Migration 153 was verified in creddit_staging; the staging build uses NEXT_PUBLIC_ANALYTICS_ENV=staging, no GA measurement ID, and only the approved operator wallet in the admin allowlist. Hourly activity retention and the staging reseed wrapper were installed while preserving the other scheduled jobs. Attended maintenance completed successfully at 08:00 UTC. Synthetic checks passed for identity, ingestion, event deduplication and account isolation; the synthetic account was removed afterward.

The additive migration creates account activity identities, raw events and daily summaries with application grants. Staging automatically applies it during deployment. The staging reset cron must call the staging checkout's scripts/ops/reseed-staging-with-migrations.sh wrapper so staged schema is reapplied after a scrubbed production-backup restore. Install the staging user-state maintenance schedule from the runbook and validate it against creddit_staging. Configure staging with NEXT_PUBLIC_ANALYTICS_ENV=staging and no GA measurement ID before building.

Production completed 2026-10-18: release PR #1190 merged as 78b4be5de9eb3c05ffd04b554924ac76352a9f4c; production deploy 39176437102 confirmed app/database health and the app, ingester and ledger-worker restarts at 23:26:37. v0.94.0 was published. Before promotion, the complete local release checks, independent review, full release CI 39174257681, and full real-data staging smoke passed. CI covered 9,092 unit tests, 272 fixture tests, 40 zoom cases, the narrow suite and all 676 desktop cases; two desktop cases passed on their permitted retry and were independently assessed as test timing. The final staging smoke passed 34 cases with 14 expected signed-in/fixture-only skips and no retries.

The standard backup runner created /opt/backups/creddit-2026-10-18T232153Z.dump (2.0 GB), verified its restore table of contents at 23:24:47 and retained 19 dumps under the existing retention policy. Disposable npm cache cleanup provided build/backup headroom. The migration runner then applied exactly 153-account-activity.sql; the ledger entry, 20 seeded identities and application INSERT grant were verified. The protected server directory /root/creddit-release-v0.94.0-20261018T232151Z preserves the previous environment/crontab and operational logs. No bespoke financial backfill was required by this migration.

Before building, production was configured with NEXT_PUBLIC_ANALYTICS_ENV=production, measurement ID G-1YH0S0DZR9 and only the documented approved operator in ADMIN_WALLETS. The user explicitly confirmed Enhanced measurement disabled on GA4 stream 16149932880; the Google UI was not independently inspected. The old property's historical data was preserved. A production browser check verified the new stream, disabled automatic page views and disabled advertising signals, with all external telemetry intercepted locally.

Hourly production maintenance was installed at minute 17 while preserving every existing cron entry. Its first attended run completed successfully at 23:27, with notification credentials removed. The public render smoke passed all nine cases with no retries. The admin API returned 401 signed out, 403 for an unapproved wallet and 200 for the approved operator, each with private/no-store caching. Post-restart ingestion succeeded across 14 streams; 98 fresh scan receipts and 325 recent raw events were checked, with no missing block hashes or whole-cycle errors. Staging was fast-forwarded to the production merge and deployment 39176666518 passed.

Additional operational recovery: verification found that the existing 06:50, 12:50 and 18:50 Portfolio snapshot runs had failed on RPC HTTP 429 before this release. After the unchanged provider answered normally, the standard snapshot job was rerun at 23:33 under its usual single-flight lock, with notifications disabled. It wrote 92 snapshot rows for 13 wallets. The restarted worker completed all 13 resulting sweep jobs without failures; the tick cursor advanced to block 26222690 at 23:33:22. The 12 reading audits were deferred until ingestion and derivation reach the new reading block, as their queue reasons confirmed. The producer remained current and the worker heartbeat fresh. No provider configuration or accounting formula changed.

History recovery receipts and persistent gap alert (migration 154) ​

  • belongs to: bounded outage recovery and historical gap alert
  • executed: 2026-10-19

Production execution, 2026-10-19. v0.95.0 deployed as 673fd46774380223d38de185879dbe41350122dc; migration 154 was applied with 155 at 18:58:17Z after the verified production backup recorded under migration 155. The initial preview found 1,380 missing checkpoints: 1,356 market observations and 24 Portfolio checkpoints. The first bounded apply preserved 1,000 restored market observations, then stopped at its unchanged 10,000-request cap: remaining=380, derived=false, unverifiedAudits=0, stopped=true, exit 1. The stop was the local cap, with no provider quota failure recorded.

Owner-requested scope change. During the release, the owner said not to restore wallet histories and then explicitly requested deletion of every existing account and wallet. After the run exited, the account reset removed those users and their Portfolio recovery receipts. No Portfolio repair or reading audit was performed. Market receipts were preserved; a new SQL-only preview found exactly 356 remaining market observations and no wallet gaps. The repair and completion checks below therefore apply to market data for this execution.

The recovery blockers were fixed in independently reviewed PR #1206, then shipped in v0.95.1 / PR #1207, merge d77c23157a376208706c71728d240be8cca2d270. Final release CI 39315573979 passed 9,304 unit tests, 276 fixture tests, 687 desktop checks, 11 narrow checks and 40 zoom checks. The version-bump staging smoke passed 34 checks with 14 expected skips. Production deploy 39319517115 completed at 20:29:14Z with all three processes restarted and app/database health passing. Ethereum and Arbitrum historical reads both returned HTTP 200 before the second bounded apply. The owner enabled Arbitrum on the existing archive provider; the server's Arbitrum archive endpoint was configured and the three missing sUSDai anchors were verified before resuming.

The second apply retained the original inclusive bounds, 250ms pacing and 10,000-request cap. It restored all remaining 356 observations using 3,642 HTTP attempts and exited zero with remaining=0, derived=true, unverifiedAudits=0, stopped=false. Together the two runs restored all 1,356 missing market observations. The standalone history checker then reported No unresolved bracketed six-hour history gaps, exit 0. No unrelated pending or derived-work receipts remained outside the incident.

After recovery, the normal quality step ran under the refresh-assets lock with external notifications disabled. It judged 18,058 readings and changed 77 verdicts: 14 token-yield launch flags, 48 Fluid thin-pool flags, three Aave launch flags and 12 Pendle launch flags. The current asset refresher reported 19 ok, zero failed, completing at 20:46:24Z.

The collateral refresh had committed 102 rows. Five upstream Fluid resolver calls still reverted; usable collateral remains published with missing amounts unattributed and capacity bounds withheld. Fluid USDS was skipped and has no stored exposure snapshot, so its exposure remains unavailable. The process correctly exited 1 to retain this upstream limitation; it is not a claim of complete collateral coverage.

The same production release was rebuilt after the data writes in deployment 39319517115, attempt 2, completing at 20:48:19Z. The app, ingester and worker all started after the new build. Origin and public health returned HTTP 200 with the database up; the quality status returned numeric judgedThrough. Accounts, wallet links, Portfolio readings and flows, derivation jobs, wallet recovery receipts and unresolved incident receipts all remained zero.

The attended invocation of the normal hourly checker at 20:48Z exited zero: ingester fresh; all 14 followed feeds within the six-hour bound; fresh worker heartbeat; zero queued, running, failed or partial jobs; no unexplained ledger adjustments; and no unresolved bracketed history gaps. The existing schedule remains unchanged. Staging was fast-forwarded to the production merge and deploy 39319802350 passed; its smoke was skipped because the synchronization changed no page. The earlier version-bump run supplied the complete real-data smoke.

Protected run logs and backups remain on the server, with copies of non-secret verification logs retained by the operator. Private credentials and user identifiers are not included in this log. The scope limitations in the recovery runbook still apply, including unavailable historical Pendle liquidity.

Required release completion step: repair the 2026-10-18 RPC outage. On 2026-10-19 the owner instructed that the release operator run this repair as part of the release. Once the production release is authorized and deployed, complete the bounded recovery below without asking again for repair approval. Deploying the code and applying the migration alone do not complete this release step.

1. Prepare the deployed production checkout. Confirm the release includes both the recovery tooling (#1196) and the Pendle cadence fix (#1197). Use the release's verified database backup, confirm /opt/onchain-credit/.env.local selects creddit, and apply 154-history-recovery-items.sql through the migration runner. Staging applies the additive migration automatically. Confirm archive RPC service and quota have recovered before applying data repairs. No new cron entry is needed: the existing hourly ingester-freshness command checks historical coverage too. Until the migration is present it reports coverage as unmeasured and exits nonzero.

2. Preview the incident interval. These inclusive UTC bounds cover the missed 06:00, 12:00 and 18:00 checkpoints. Run from the deployed production checkout:

sh
cd /opt/onchain-credit
node --env-file=.env.local --import tsx scripts/recover-history.ts \
  --from 2026-10-18T06:00:00Z --to 2026-10-18T18:00:00Z \
  --pace-ms 250 --max-requests 10000

Save the deployed commit and preview output with the release evidence. The staging preview found 1,356 missing market observations across nine series; production's preview is authoritative and also includes any wholly absent Portfolio checkpoints. Read the coverage limitations in the output and the attended recovery runbook. Preview is SQL-only; its zero exit status does not prove the data has been repaired.

3. Apply the repair and finish its audits. Run the same interval with writes enabled, preserving the per-run request cap and pacing:

sh
node --env-file=.env.local --import tsx scripts/recover-history.ts \
  --from 2026-10-18T06:00:00Z --to 2026-10-18T18:00:00Z \
  --pace-ms 250 --max-requests 10000 --apply

Save every run's output and exit status. Successful history is preserved, and the command recalculates dependent yields and basis and queues Portfolio reading audits. Let the worker finish those audits, then rerun the same bounded --apply command to settle their receipts and verify completion. If interrupted or stopped by quota or the request cap, inspect the cause and available quota before resuming with the same command; do not loop automatically or raise the cap to bypass a provider failure. Missing archive inputs and failed audits remain outstanding.

4. Verify before reporting the release complete. The final apply must exit zero and report all of remaining=0, derived=true, unverifiedAudits=0 and stopped=false. Then run the historical coverage check:

sh
node --env-file=.env.local --import tsx scripts/check-history-gaps.ts

Confirm this incident has no pending gaps, dependent calculations or audits, and that the next hourly check no longer reports it. Any unrelated gaps remain separate findings; do not clear their receipts to silence the alert. Record the production commit, migration, backup, applied counts, final summary and audit verification here. Set executed: to the proven production date only after these checks pass. If the code ships while recovery is blocked, set it to outstanding and report the remaining work; do not mark the incident repaired. Current-only state, partial Portfolio checkpoints and unavailable historical API fields retain the coverage limitations documented in the recovery runbook.

v0.95.0 production account reset, requested during release ​

  • belongs to: the owner's explicit instruction to delete all existing production accounts and wallets instead of restoring their histories
  • executed: 2026-10-19

The attended outage recovery had exited before the reset began. Between six-hour collection ticks, the operator stopped the ledger worker and saved that state, took and verified a comprehensive data-only backup of user state and its non-cascading records, then ran the documented reset first as a rolled-back dry run and then with the database-name confirmation. Protected backups and exact before/after counts remain in the operator's server evidence bundle.

The reset removed all production accounts, tracked-wallet links, Portfolio readings and flows, wallet indexes and backfill state, pre-window PT fills and account activity. Per-wallet cursors and derivation jobs were removed while chain-wide cursors were preserved. After restarting the ingester, the operator cleared wallet coverage, held-PT state and any accountless jobs. Portfolio recovery receipts were also removed because migration 154 has no account foreign key; market receipts were preserved. This implements the deletion request and does not claim those users' histories were recovered or audited.

The session secret was rotated, and the app, ingester and worker were restarted. A cookie signed with the former secret returned HTTP 401; the replacement secret was verified active. The ingester reported zero enrolled wallets, every checked user-state count was zero, and application/database health passed. No on-chain transaction was sent. The remaining release recovery is limited to market data.

v0.97.0 production account deletions, requested after release ​

  • belongs to: the owner's explicit instructions on 2026-10-22 to delete every account except 0x46a2…b1f2, then that account too
  • executed: 2026-10-22

Partial delete, 09:00Z. Between six-hour ticks, with the ledger worker stopped and saved stopped, and after a data-only backup (/root/backup-users-2026-10-22.sql), the documented some-wallets transaction deleted six accounts (0x5226…0dec, 0xaae6…d050, 0xd183…17cb, 0x3dab…1d91, 0x6f5d…5555, 0x795c…9a35); no kept account tracked any of them. It removed 12 wallet coverage rows, 218 derivation jobs and 22 per-wallet cursors. The session secret was rotated in .env.local, but the app was restarted without the file sourced, and pm2's stored process environment kept the former secret (Next does not override an existing variable), so an old session still verified. Fixed by restarting the app with .env.local sourced; a cookie signed with the former secret then returned "Not signed in". The operator's verification cookie, signed with the new secret, re-created 0xd183…17cb's account at 09:04Z.

Full wipe, 09:50Z. Worker stopped and saved, backup /root/backup-users-2026-10-22-full.sql, reset-portfolio-users.ts dry run then --execute --confirm-db=creddit: 4 account rows for 4 wallets, of which 2 were signed-in users (0x46a2…b1f2 and the re-created 0xd183…17cb) and 2 the shadow rows a tracked wallet gets (0x46a2…b1f2's 0xdf87…cee2 and 0xc130…d6c9, never signed in), plus 111 derivation jobs and 15 cursors. The secret was rotated again and the app restarted with the file sourced, then the ingester. Step 4's clean-ups ran: 8 wallet and native-ether coverage rows, 6 held-PT rows, the Portfolio recovery receipts (none remain) and the accountless derivation jobs. The ledger worker was then started and saved running (confirmed online in pm2's saved process list on 2026-10-22). The app runs the new secret, a former-secret cookie returns "Not signed in", the ingester reports enrolled wallets: 0, and the main pages return 200. Production has no accounts (as of 2026-10-22 09:55Z; two wallets signed in afresh later that day, after the rotation). Former environment files: /root/.env.local.bak-20261022 and /root/.env.local.bak-20261022b.

v0.95 quote provider configuration ​

  • belongs to: the Fynd-first quote service and its shared fallback paths, PRs #1202 and #1204
  • executed: 2026-10-19

The existing hosted Fynd credential was configured in production after a protected environment backup. Live quote-only checks confirmed the primary provider and a deliberately selected Kyber fallback both returned HTTP 200 and positive output for the same small ETH-to-USDC input. The release also includes the independently validated Pendle receiver fix for PT fallback. No transaction was submitted. Credentials remain on the server and are absent from this record.

Migration 157: shared Morpho market coverage and observations ​

  • belongs to: migration 157-morpho-market-primitive.sql and the shared Morpho market readers
  • executed: 2026-10-22
  • mandatory: Apply the additive migration, initialize shared market observations and coverage, fill the existing app markets' supported history, judge the new rate series, and verify the four consuming screens before completing the production release.

This entry records work for the release that deploys the feature. Preparing its feature PR does not authorize production writes. Keep the previous release's columns in place for rollback; this migration drops no table or column.

  1. Follow the normal backup and migration procedure. Apply migration 157 before running the new collection code. The app can build before the migration; common market fields remain unavailable until the shared observations exist.
  2. Run the normal six-hour assets refresh once from the deployed checkout. Its Morpho step discovers descriptors, evaluates coverage, fills recent admission history, and writes current observations. Its funds step writes observations at each allocation's exact block. The final quality pass judges those spot rates. Keep the run log and investigate any per-market failures.
  3. Fill existing Morpho history from 2026-01-01 UTC, or creation if later, using backfill-morpho.ts --from 2026-01-01 --sleep-ms 250. The default repair scope preserves each market's existing stored span and also populates shared state for it. Process bounded date ranges with --to and retain the printed --since checkpoint for an interrupted run. Do not request pre-January history. Existing older rows remain stored. Newly admitted markets' deeper history is filled by the bounded automatic queue; it must not delay their recent rates. Use --extend-history only when intentionally extending the admitted markets within the same January floor.
  4. Run the series re-judge for morpho_market_apy and morpho_market_state using the attended procedure in the data pipeline documentation. Verify that rejected rates are withheld while raw balances and indexes remain readable.
  5. Verify a market shared by Repo Lending and Portfolio has the same measured 24h APY, and that Carry Trades uses the same underlying market history. Verify a Money Market Funds allocation joins the shared observation at its allocation block; a missing exact-block observation must not use a later one. Confirm Portfolio quantities, balances, ledger and valuation behavior remain unchanged. Record the deployed commit, migration, run outcomes, covered date ranges and unresolved historical gaps here before dating executed:.

Production execution (v0.97.0, deploy commit d2487c71). Step 1: migration 157 applied at 19:58:01Z on 2026-10-21 (see migration 158); the production backup of 02:15Z on 2026-10-22 was the restore point for the data steps. Step 2: the scheduled six-hour assets refresh ran at 00:00Z and 06:00Z on 2026-10-22 on the deployed code (morpho step: 206 of 206 active markets ok, 0 failed; 36 exposure rows), and once more by hand at 10:05Z (18 ok, 0 failed, 0 partial). Step 3: backfill-morpho.ts --from 2026-01-01 --sleep-ms 250, 08:36Z to 10:01Z: 1,178 six-hour windows from 2026-01-01T00:00Z to 2026-10-22T06:00Z, ok=96328 failed=0 lostWindows=0. Shared state afterwards: 193,133 morpho_market_state rows over 222 markets from 2026-01-01, 1,841 coverage rows. No pre-January history was requested. Step 4: rejudge-series.ts --tables=morpho_market_apy,morpho_market_state,token_yield_apy,token_basis, dry run then --execute --confirm-db=creddit at 10:03Z: 593,978 readings judged, 32,732 changed (morpho_market_apy out_of_range 7,380, launch_window 2,345, cleared 132; morpho_market_state out_of_range 14,645, launch_window 7,722, cleared 424; token_basis launch_window 80, cleared 4; token_yield_apy none). The out-of-range rejections are wound-down markets whose stored supply rates read hundreds of thousands of percent (for example USDC/sdeUSD at 246,095.84% on 2026-01-01); raw balances and indexes stay readable. Backup: /var/tmp/rejudge-series/rejudge-series-creddit-2026-10-22T100307553Z.jsonl. --verify PASS. The run reports history not marked judged because only these four tables were judged. Step 5: Repo Lending's Morpho fxSAVE/USDC 24h APY (1.5669%) equals the shared supply_apy_24h; Carry Trades reads the same market history. The cached Repo Lending page had been rendered before step 3 and served no 7-day or 30-day APY for any of its 35 Morpho rows; after its regeneration every Morpho row has both (fxSAVE/USDC 2.443% and 3.799%). Money Market Funds: 394 of 394 Morpho allocations of the latest read join the shared observation at their exact block, none missing. Portfolio was not checked against a wallet: production had no enrolled account holding a Morpho position, and every account was deleted on 2026-10-22 at the owner's request. Unresolved gaps: none reported by the backfill.

Five retained database backups ​

  • belongs to: scripts/ops/backup-creddit.sh and prune-backups.py, owner-requested maintenance on 2026-10-21
  • executed: 2026-10-21

The owner requested five retained backups instead of the former 14-day age policy. The limit counts the newest five completed timestamped dumps, scheduled and manual combined; it is a count of restore points, not a promise of five calendar days. Partial dumps, other databases, symlinks and unrelated files are excluded. Before deleting any older dump, the helper reads and decompresses every retained archive with pg_restore --file=/dev/null, without connecting to a database. A failed verification, an incomplete backup or a changed file prevents cleanup. The nightly writer serializes concurrent invocations and only invokes cleanup after its new dump passes the existing integrity check. BACKUP_RETENTION_COUNT overrides the default five.

Install the reviewed standalone helper at /usr/local/lib/creddit/prune-backups.py as the specifically authorized backup-maintenance change. Keep the deployed production backup writer unchanged. The nightly cron disables its legacy age-based cleanup with BACKUP_RETENTION_DAYS=365000, sets BACKUP_RETENTION_COUNT=5 for compatibility with the next writer version, and invokes the standalone helper after a successful backup. This does not deploy application code or authorize a production application release. Run the helper without --execute first, then execute the same plan, record retained filenames and reclaimed disk space, and verify the installed helper and nightly cron. Keep this record separate from the strUSD staging backfills it unblocks.

Execution record (2026-10-21). Installed the independently reviewed helper with SHA-256 c336d101d89272ced9609f91de3d8ddee649a19117ee8b9d85dc00e0b68c1b00 and applied the cron wrapper above, preserving all other cron entries. The production backup writer remained unchanged (SHA-256 cc201298fbc9f67ee6d357f47e367229a425b7daea25191d51f35e6604ba1d34). The initial read-only plan found 20 completed dumps. All five retained archives passed a complete pg_restore read/decompression before 15 older dumps were removed. Retained timestamps (UTC): 2026-10-21 02:15:01, 2026-10-20 02:15:01, 2026-10-19 18:54:50, 2026-10-19 02:15:01 and 2026-10-18 23:21:53. These are five restore points spanning four dates. Root filesystem available space increased from approximately 5 GiB to 34 GiB (77% used), clearing the 25 GiB historical-backfill prerequisite. The installed cron matched the prepared entry byte-for-byte. The protected on-host record is /root/creddit-backup-retention-20261021 (plan, execution log and before/after crontabs). No database writes or production application deployment were part of this maintenance.

Tori strUSD coverage (migration 156, issue #1031) ​

  • belongs to: migration 156-tori-strusd.sql, the strUSD profile and tori-strusd-cooldown
  • executed: 2026-10-22
  • mandatory: Run the registry, historical price/rate, ingestion, affected-wallet and reconciliation checks below in order in the release that ships migration 156. Record results here. A staging feature merge does not authorize production operations.
  • staging: completed 2026-10-21; execution and remaining history limitations recorded below.

Economics. strUSD is a USD Variable rate asset, credit_rwa, market-priced from its own USD tape with one explicit CoinGecko backup. Its accrual rate is convertToAssets(1e18) / 1e18 trUSD per share at dollar par. The market quote already incorporates trUSD/USD, so it must not be multiplied by trUSD's market price again. USD basis includes both the share's secondary discount and trUSD's depeg. trUSD already has its own USD/par registry row and market feed. Productive and underlying capitalization use the actual trUSD/USD price. Negative share-rate returns remain losses, subject to the normal series-quality verdicts.

Recorded evidence. Ethereum block 26,239,892 (2026-10-21 08:51:35 UTC): rate 1.032595068242610024, previewRedeem(1e18) equal to it, cooldown 604800 seconds, silo 0xf7c0d8853e69dcd37ee7599c6280d2632f3360b4, implementation 0x6561272e3ebc9f2e07cdb12b7c474db9132b977a (1.1.0). The token first has code at block 25,275,301; the preceding block has none. derive/fixtures/recorded-tori.json contains raw receipts, calldata and archive returndata for a mint, completed cooldown, two cancellations, repeated requests and waiting/ready claims. The initial implementation was 0x521e98ba48e58d34293d9628e76c1b6e366906ff; its verified 1.0.0 source was checked: request accumulation, owner-keyed full claim, cancellation at the current share rate, seizure and zero-duration withdrawal have the same lifecycle semantics. Both implementations return a uint256 underlying amount. The complete upgrade-event scan from deployment through block 26,239,892 contains only the initial implementation and the upgrade to 1.1.0 at block 26,089,623; those raw logs are retained in the recording.

The 30 complete UTC days ending 2026-10-21 have 30 trading days, median daily vendor volume $142,770.20 and $2,667,788.03 in the Curve strUSD/trUSD pool (0x25a637c80ad90177d0b3ff28aa2d3f74f7165ccb). Volume uses the latest trailing-24h observation in each day, matching foldDailyVolumes. Curve's null Dune dollar amounts are not zero volume. These clear the secondary-market thresholds; the seven-day primary exit is not atomic. Dune alone had 345 of 720 hours and stopped at October 14 08:00, hence the explicit backup. No synthetic market-at-redemption substitution or enlarged stale-price allowance is permitted.

Order, in the selected environment. Staging uses /opt/onchain-credit-staging and creddit_staging; production uses /opt/onchain-credit and creddit only during its explicitly authorized release. Source that checkout's .env.local without printing credentials; retain command logs and the deployed commit.

  1. Before any repair, run scripts/ops/restate-covered-readings.ts --plan and inventory strUSD/trUSD in readings AND flow-only histories, plus open cooldowns(owner) at each enrolled wallet's history floor and present block. Include all enrolled wallets, not only wallets currently holding shares. Check the issue wallet 0x1929d726442305465f7d0996be32c71ba2b5f45a separately. It had 118,703.053834324846162917 strUSD collateral in Morpho market 0x975c6e8b71073a82216ae464bc44f67d71988450d2542d635d88bc78fca344b1 at the evidence block and no stored portfolio snapshots; that does not rule out flow-only impact.
  2. Deploy queue-aware code and apply migration 156 with the ledger runner. Verify the registry row, its profile, exit_queue, trUSD dependency and the new ERC-4626 rate adapter. Run npm run verify:escrow-registry; the asset/silo assertions must match, and review any implementation-pin report. Restart the selected environment's ingester/worker where they run so their token universes include strUSD.
  3. Backfill six-hourly share rates with scripts/ops/backfill-token-rate-series.ts --token 0x280839980a7ed0d7717f64125fe241012e5f5815 --days N --plan, then the same with --execute. Choose N to reach the first six-hour boundary AFTER block 25,275,301; no reads before deployment and no fabricated par history. Confirm timestamps, actual block intervals, supply, 24h and 30d returns, and run the existing series-quality judge. Missing early history must stay disclosed.
  4. Load the two market series with scripts/backfill-token-price-bars.ts <deployment-UTC-date> --tokens=0x280839980a7ed0d7717f64125fe241012e5f5815,0xd0580192e98ea6ceb9c7b6191ed2e27560911697. Run the normal price-bar refresh and its fillHistoryHoles backup path scoped to these tokens until their available historical coverage is accounted for. Use its existing vendor-history cursor, bounded call budget and quality checks. Record accepted/rejected hours, first/last hours, outstanding gaps and vendor limitations; do not declare a complete range from an empty successful vendor response. Recompute basis and refresh the profile only after these facts are available.
  5. Backfill and verify the expanded erc4626 stream from its coverage floor through the selected head (scripts/backfill-event-ledger.ts --stream erc4626 --from … --to …, then completion and --verify under the standing ledger procedure). strUSD's request uses the existing ERC-4626 Withdraw stream, with receiver equal to the silo; it is not duplicated in escrow. Closures are found by owner-keyed archive state and proven by receipt/call evidence. Review historical upgrades and record the coverage evidence before certifying the expanded stream.
  6. Re-run the coverage restatement plan. Execute it for the affected wallet set and drain the selected environment's bounded worker as documented in Deployment. Include flow-only wallets from step 1 even when the reading plan is empty. Reconcile the complete lifecycle, entry basis and carry position; check there are no unexplained quantities, artificial capital movements or missing claims. Unavailable owner proof must withhold the affected derivation.
  7. Run scripts/sync-carries.ts --dry-run. The existing strUSD/USDC Morpho market should no longer be blocked for a missing yield adapter once its fresh series exists. Other admission criteria still apply; this release does not approve additional markets. Verify collateral, loan and oracle configuration against the same block as the position check.
  8. Validate /asset-profiles?asset=strUSD, the USD Positions view (bare shares, Morpho collateral and In settlement) and Activity. A pending claim holds fixed trUSD, stops accruing share yield and remains exposed to trUSD/USD. Cancellation preserves entry history while reminting at the then-current rate; seizure to another address is capital leaving. Verify waiting, ready, blacklist and duration-zero facts. Record the staging smoke and post-operation checks here.

Staging execution, 2026-10-21. Migration 156 was applied at 11:56 UTC by PR #1233, commit d3640772618ed36bf973d80a8e0a86d6343c7659. Deployment and real-data browser smoke passed. The separate backup-retention operation recorded in Backup retention freed the capacity required for the attended historical sweep; the filesystem had 34 GiB available. All asset operations used creddit_staging. No production asset migration, backfill, worker or application deployment was performed.

  • The before/after inventory found zero enrolled staging accounts, zero affected readings or flow-only histories, and therefore no enrolled-wallet cooldown or restatement population. This is not a claim that the issue wallet has no position: independent reads at block 26,240,771 confirmed 118,703.053834324846162917 strUSD collateral in the existing Morpho market, zero bare strUSD and trUSD, zero pending cooldown, and the registered collateral, USDC loan, oracle and 86% LLTV. No user account was enrolled for this check.
  • All 65 escrow-registry assertions passed, including the asset/silo and implementation checks. Staging runs no standing ingester or worker; its ledger work was an attended foreground process.
  • 539 of 539 six-hour rate boundaries were populated, from 2026-06-09 00:00 through 2026-10-21 12:00 UTC, with zero read errors and no pre-deployment reads. At the last boundary the share rate was 1.0326266431205557, supply 60,373,672.78126309, annualized 24-hour return 8.966554243455183% and annualized 30-day return 10.46141366036959%. The series judge marked the 44 launch-window rate observations and its verification passed.
  • The scoped Dune history, normal 48-hour refresh and bounded vendor hole-filling runs produced 2,049 accepted strUSD hours (2,001 CoinGecko, 48 Dune) and 2,059 accepted trUSD hours (97 CoinGecko, 1,962 Dune) from June 9 onward, with zero rejected hours. First usable prices were July 27 15:00 for strUSD and July 27 14:00 for trUSD; last usable hours at validation were October 21 06:00 and 08:00, respectively. Missing history remains 1,174 strUSD hours (1,167 before that first usable price and seven isolated September hours) and 1,166 trUSD hours before its first usable price. Both deployment-day partial hours were also unavailable. Seven bounded older windows used ten CoinGecko calls and returned no further usable early prices; there were no refusals, deferred spans, disagreements or spike rejections in those runs. Both sync records have a completed history-floor load. Missing vendor observations were not replaced with par or redemption values.
  • PR #1236, staging commit 3e80fd00e5ebab1785ccac514ddd185f0accd78a, adds both tokens to scheduled basis maintenance, with strUSD using the USD share-rate reference and trUSD the USD par reference. Its independently reviewed final head passed checks and the browser zoom sweep. At 12:35 UTC, the deployed default basisTokens() registry returned both assets with USD references, strUSD share_rate and trUSD par, and final database reads reconfirmed the rate/basis counts, formulas, profile and live event certificates listed here. The follow-up staging deployment and real-data browser smoke both passed.
  • Basis replay evaluated 1,078 token/boundary pairs: 688 written, 390 missing market price, zero errors, producing 344 observations per token from July 27 18:00 through October 21 12:00 UTC. Maximum absolute formula residual was 2.184e-16. At the last boundary strUSD basis was 1.0309785149179382 / 1.0326266431205557 - 1 and trUSD basis was 1.000141562446636 / 1 - 1; the share quote was not multiplied by trUSD/USD again. The judge marked 40 launch observations per basis series, rejected none, and passed verification. The profile refresh succeeded for all 20 profiles; strUSD productive capitalization was $62,352,374.47 and underlying capitalization $72,088,799.70, using the actual trUSD market quote.
  • The expanded ERC-4626 stream swept 24,136,053 through 26,240,771 in 43 windows, inserting 2,636 events. Completion and a separate final --verify both passed all four conditions. The frozen acceptance range [24,136,053, 25,840,566] contained 788,361 measured-universe rows against the recorded [784,903, 798,903] band; 2,594 scan receipts had no gap, the independent provider matched the sampled digests, both named anchors were present, and 642/642 declared addresses had live certificates. Final verification tag: 61f3afe4e7c7. strUSD's per-address certificate is live from 24,136,053 through 26,240,771. The final ledger occupied 19,999,064,064 bytes, an increase of 2,711,552 bytes during this sweep. The post-coverage restatement plan found nothing to restate; with no enrolled accounts or flow-only wallets there was no affected worker queue to drain.
  • Carry synchronization ran in dry-run mode only, with no writes. The existing strUSD/USDC market no longer classified as blocked_adapter; it was proposed by the carry classifier. Its oracle card still lacks approved blocks for strUSD against USDC. This operation did not approve an oracle card or additional markets.
  • Recorded-chain lifecycle tests and the three fixture browser cases cover bare shares, Morpho collateral, fixed-trUSD settlement, claim/cancellation and owner-proof withholding; final feature CI and the staging smoke passed. The staging database's empty account population means this is not live enrolled-user portfolio reconciliation. Blacklist, duration-zero and seizure behavior remain guarded by the explicit contract evidence and lifecycle tests.

Rollback. Registry and profile writes are additive. Older code understands the share-rate getter but cannot account for Tori's queue. Withhold affected wallet derivation during a rollback and restore queue-aware code before resuming it; do not erase the new claims or manufacture market prices.

Production execution, 2026-10-21 to 2026-10-22 (v0.97.0, deploy commit d2487c71). Migration 156 applied at 19:58:01Z on 2026-10-21 with the ingester and worker stopped; both restarted on the new code at 20:00:53Z.

  • Step 1: restate-covered-readings.ts --plan: nothing to restate. Two enrolled wallets (0x3dab…1d91, 0x6f5d…5555) had no strUSD or trUSD readings or flows; archive reads of cooldowns(owner) and both balances at their history floor (block 26,014,998) and at 26,247,017 were all zero. The issue wallet was not enrolled. This step ran on 2026-10-22 at 08:39Z, after step 2's migration and restart (2026-10-21 19:58Z to 20:00Z), not before it. The result is unaffected: neither wallet ever held strUSD or trUSD, so there was nothing the queue-aware code could have read or written differently in between.
  • Step 2: npm run verify:escrow-registry: 65 assertions match the chain.
  • Step 3 (2026-10-21 at 20:01Z, during the release): the backfill wrote 540 six-hour rate rows, 2026-06-09 00:00Z to 2026-10-21 18:00Z; the scheduled refreshes have added the later ones (543 rows through 2026-10-22 12:00Z, rate 1.03287270 at block 26,248,012). None is rejected; the series judge marks the launch window (launch_window: drawn on a chart from 2026-06-20 00:00 UTC), which keeps the missing early history disclosed. The step's other confirmations (block intervals, supply, 24h and 30d returns) were not recorded at the time.
  • Step 4: the scoped Dune load at 20:02Z on 2026-10-21 (backfill-token-price-bars.ts 2026-06-09 --tokens=…) gave strUSD 48 Dune hours (2026-09-30 to 2026-10-07 09:00Z). The vendor history only reaches back to the tape's last print, so on 2026-10-22 the backup path fillHistoryHoles was run scoped to strUSD in ten-day windows ending 2026-10-01 back to 2026-07-12 (overlapping by half a day, because the backup grace refuses each window's last hours): every hour written passed its quality checks, with zero disagreements and zero spike rejections. strUSD now holds 1,945 accepted hours from 2026-07-27 15:00Z, the same first usable hour as staging; 135 hours since then remain without a usable price (123 of them in the first days after 2026-07-27), and windows before 2026-07-27 returned nothing. trUSD already held its history from 2026-07-27 14:00Z. Basis replay over 2026-06-09 to 2026-10-22 06:00Z through the live writer with a database-only bar reader: 1,084 token/boundary pairs, 694 written, 390 missing a market price, 0 errors, 347 observations per token from 2026-07-27 18:00Z. The re-judge of migration 157's step 4 covered token_basis (launch_window 80, cleared 4). The 10:05Z assets refresh refreshed all 20 profiles.
  • Step 5: no expanded sweep had run on production (only live-ingester receipts), and the first --verify missed condition 3 on an August receipt. Ran backfill-event-ledger.ts --stream erc4626 --from 24136053 --to 26246964: 147 new rows on other declared vaults. The completion run then passed all four conditions and stamped 642 coverage rows live from 24,136,053, and --verify --window 1000 passed (verify PASS · run 61f3afe4e7c7). strUSD's stored Deposit (173) and Withdraw (1,496) events match an independent archive log scan of its contract from deployment to block 26,246,881 exactly.
  • Step 6: the post-coverage plan found nothing to restate; no affected wallet, so no worker queue.
  • Step 7: sync-carries.ts --dry-run: strUSD -> USDC on Morpho (morpho-strusd-usdc-975c6e8b) classifies as proposed, no longer blocked_adapter; its oracle card still lacks approved blocks. Nothing was approved.
  • Step 8: /asset-profiles?asset=strUSD returns 200 with the Tori profile. Positions and Activity could not be validated on a production wallet: no enrolled wallet held strUSD, and every account was deleted on 2026-10-22 at the owner's request. The recorded-chain lifecycle tests and fixture browser cases remain the evidence for those surfaces.

Private documentation. creddit.xyz