> ## Documentation Index
> Fetch the complete documentation index at: https://docs.moda.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# E

# E — SQL ledger

## Goal

Next job is **#11633 rewired onto the SQL executor**, not the retired engine.
Close the current owner/tenant rungs under the [architecture](../architecture.md).
The scoreboard holds current values; shadow builds are progress evidence while
published output is frozen.

## Metric

Days closed to the bill **to the nanodollar**, published by D+1 08:00 UTC, with
SQL-ledger CPU under **2% of sampled replica-host busy CPU**, using the user-approved
cycle-1 denominator instead of the previous all-finished-query denominator.
The closure diagnostic checks the latest seven completed UTC days, current SQL
manifests and signed bill/ledger totals.

Run [E-cpu.sql](E-cpu.sql) separately for the latest UTC hour whose end is at
least two minutes old, allowing query-log rows to arrive before the check. Every
replica's retained query log must cover both boundaries; otherwise the proof is
unavailable. Its
numerator reads terminal `QueryFinish`, `ExceptionBeforeStart` and
`ExceptionWhileProcessing` rows whose `log_comment` contains `sql-ledger`,
with `event_date` and tag filtering in `PREWHERE` before reading the CPU map.
It sums `OSCPUVirtualTimeMicroseconds` per replica. It does not scan all query CPU
to obtain a denominator.

The denominator time-weights `OSUserTime + OSNiceTime + OSSystemTime` from
`system.asynchronous_metric_log` across every current replica. Production metric
descriptions define these unnormalized rates as busy CPU cores summed across
the host's cores, including **all host processes**, not just query threads or
ClickHouse. Multiplying by seconds gives CPU-seconds. This is a **sampled host
CPU estimate**, including background work, not billed compute or query CPU.
The estimate holds each rate over the preceding logged interval; boundary
intervals are clipped to the hour, with at most two minutes of padding.
Duplicate-second samples are averaged.
Every host needs all three metrics covering the whole hour and no gap over ten
seconds. Missing hosts/metrics, invalid samples, zero denominator, no tagged
activity or missing CPU counters yield NULL and fail, never a passing zero.
Host replacement during the hour requires review; this query is not a historical
host-inventory audit.

Both sources fit the unchanged 1 GB read guard in the bounded design. However,
**tag completeness is not yet verified on the SQL executor deployment**: confirm
that its reads, writes, retries and cleanup all carry the `sql-ledger` marker
before treating a CPU result as exit evidence. The narrower tag scan is not
proof that untagged work is absent. Until that review and the shadow checks pass,
full E exit remains blocked. The closure query below deliberately keeps its CPU
field NULL and overall exit blocked; it cannot certify the independent CPU gate.
Equality of daily totals is a necessary diagnostic, not a replacement for the
executor's per-bill conservation/content audits or explained-difference review.

## Proof query

```sql theme={"dark"}
WITH publications AS (
  SELECT day,argMax(tuple(ledger_run_id,published_at,builder_version,provisional),
    tuple(ledger_version,published_at,ledger_run_id)) AS p
  FROM moda.cost_ledger_publications
  WHERE day>=toDate(now('UTC'))-7 AND day<toDate(now('UTC')) GROUP BY day
), bills AS (
  SELECT day,ledger_run_id,sum(toInt128(cost_nanos)) AS nanos,count() AS rows
  FROM moda.cost_ledger_bill_daily FINAL
  PREWHERE day>=toDate(now('UTC'))-7 AND day<toDate(now('UTC'))
  GROUP BY day,ledger_run_id
), ledger AS (
  SELECT day,ledger_run_id,sum(toInt128(cost_nanos)) AS nanos,count() AS rows
  FROM moda.cost_ledger_daily FINAL
  PREWHERE day>=toDate(now('UTC'))-7 AND day<toDate(now('UTC'))
  GROUP BY day,ledger_run_id
)
SELECT d.day,p.p.4 AS provisional,
  CAST(NULL AS Nullable(Float64)) AS cost_cpu_share,
  'requires_cpu_companion_and_tag_audit' AS cpu_budget_proof,
  toUInt8(p.p.1!='' AND p.p.3!='' AND b.rows>0 AND l.rows>0 AND b.nanos=l.nanos
    AND p.p.2<=toDateTime(d.day+1,'UTC')+INTERVAL 8 HOUR) AS closed_on_time,
  toUInt8(0) AS exit_pass
FROM (SELECT toDate(now('UTC'))-1-toInt32(number) AS day FROM numbers(7)) AS d
LEFT JOIN publications AS p ON d.day=p.day
LEFT JOIN bills AS b ON b.day=d.day AND b.ledger_run_id=p.p.1
LEFT JOIN ledger AS l ON l.day=d.day AND l.ledger_run_id=p.p.1
ORDER BY d.day
SETTINGS readonly=2,max_threads=1,max_bytes_to_read=1000000000,max_result_rows=1000,
  max_execution_time=30,read_overflow_mode='throw',result_overflow_mode='throw'
```

## PRs to adopt now

From the [merged map](../pr-lane-map.md): #11633 is next. Check #11550, #11523 and
\#11509 **against the SQL ledger**, preserving bill-key splits, invalidation and
instrumentation checks without old-engine coupling. #11640 is merged. #11532
was reverted by #11636: do not re-land. #11512 and #11545 are designated for
closure, not adoption. Keep legacy rating running until its Cloudflare-estimate
dependency is replaced. Delete replaced execution code in the stop/deletion stack.

\#11642's old-ledger retirement stays in E and depends on #11646 landing first.
That architect correction moves the CI planner, ledger-load/schema-wait scripts,
instrumentation and wiring/retirement tests from C/D to E. The CI planner reads
ledger tables, so those helpers and tests follow E's existing `index.ts` and
`clickhouse.ts` ownership. It does not transfer bill collectors or production
ClickHouse basis allocation from C/D, or authorize drops/deploys.

## Stop-and-ask conditions

Ask before **publishing, any table drop, or any deploy**. First compare Nov 11–12
shadow builds to old published days: equal bill totals and explained differences.
Then use the seven-day provisional acceptance window before final acceptance.
Keep `buildLedger` only as frozen test comparison. Rollback retains the last
publication; it never restarts the old path. Follow [standing rules](README.md).

## Exit check

Every generated day must have `closed_on_time=1`, the CPU companion must have
`exit_pass=1` with verified tag completeness, and the combined exit remains blocked
until all evidence is reviewed. Missing days cannot disappear from the result.
Additionally require per-bill audits, approved shadow differences and
the seven-day provisional acceptance evidence. A nonempty builder version alone
does not certify the SQL executor: verify it against #11633's approved version.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.