From 92589f02bc54e860c61e1f88f590cf81720570d2 Mon Sep 17 00:00:00 2001 From: v1rtl Date: Tue, 29 Sep 2026 15:36:31 +0200 Subject: [PATCH 1/2] fix(api): report a stalled indexer when there is no finality data stale on /ready, /coverage and _coverage came only from the safe-head comparison and answered false whenever finality data was absent, so a deployment without FINALITY_ENABLED looked healthy however far behind it fell. graphql.ens.dev sat ~40h behind Sepolia reporting stale:false. COVERAGE_STALE_AFTER_SECONDS (opt-in, default 0) adds a fallback when there is no safe position: stale when any indexed protocol has gone longer than the threshold without committing a batch, or when nothing has synced at all. Finality data still decides on its own when present. - One live protocol no longer masks a dead one: the fold is an OR over protocols with a sync_state row, not max(last_synced_at). - Never-synced reads stale once armed instead of healthy forever. - A timestamp ahead of the API clock reads as age 0 and warns once per process; the subtraction saturates on hostile DB values. - Off by default: healthy bulk-sync batches have taken 10-44 min, and --backfill and END_BLOCK-pinned deployments never advance the head. - off/false/no parse as disabled; any other non-integer is logged instead of silently becoming a threshold. - /ready, /coverage, _coverage and /metrics share coverageStale. The existing ensv2_indexing_stale gauge keeps its _finality.isStale meaning; the new ensv2_coverage_stale gauge mirrors /coverage. --- .env.example | 11 ++ schema.graphql | 8 +- src/api/api_endpoints.zig | 67 ++++++----- src/api/common.zig | 152 +++++++++++++++++++++++++ src/api/resolvers/admin.zig | 10 +- src/api/resolvers/common.zig | 2 + src/api_main.zig | 1 + src/config.zig | 35 ++++++ src/storage/database.zig | 10 ++ src/storage/pool.zig | 4 + tests/conformance/runner.zig | 55 +++++++++ tests/storage/pool_test.zig | 16 +++ tests/storage/postgres_driver_test.zig | 1 + 13 files changed, 335 insertions(+), 37 deletions(-) diff --git a/.env.example b/.env.example index a442107..5059fbf 100644 --- a/.env.example +++ b/.env.example @@ -113,6 +113,17 @@ METRICS_ENABLED=false # always present but returns nulls until enabled). Cheap: 2 extra RPC calls per poll. # FINALITY_ENABLED=false +# API only. On a deployment with NO finality data, /ready, /coverage, `_coverage` and +# the ensv2_coverage_stale gauge report stale=true once any indexed protocol has gone +# this many seconds without committing a batch, or when nothing has synced at all. +# Ignored when finality data is present (the safe-head comparison wins). +# Off by default (0 / off). The shipped docker-compose files set 3600. +# - Must exceed your longest healthy batch: bulk-sync batches have taken 10-44 min. +# - --backfill and END_BLOCK-pinned deployments do not advance the head and WILL read +# stale; set 0 for those. +# - Compares the indexer host's clock with the API host's; keep both NTP-synced. +# COVERAGE_STALE_AFTER_SECONDS=3600 + # Query-time Resolution (all OFF by default — served values are byte-identical # until explicitly enabled). See docs/tasks/04-06. # Dedicated resolution RPC endpoint (defaults to RPC_URL when unset): diff --git a/schema.graphql b/schema.graphql index 6f469a7..007a17f 100644 --- a/schema.graphql +++ b/schema.graphql @@ -131,8 +131,10 @@ type Query { """ What this deployment indexes (ensv2 extension): chain id, per-protocol indexed - head + last-sync time, and a staleness flag. `stale` is false when finality data - is absent (default deployments); `_finality.isStale` is the conservative variant. + head + last-sync time, and a staleness flag. Without finality data `stale` can + fall back to how long each protocol has gone without committing a batch (opt-in, + `COVERAGE_STALE_AFTER_SECONDS`); `_finality.isStale` remains the conservative + variant (true whenever no safe data). """ _coverage: Coverage! } @@ -141,7 +143,7 @@ type Query { type Coverage { """EVM chain id this deployment indexes.""" chainId: Int! - """True only when finality data shows the indexed head behind the chain's safe point.""" + """True when the indexed head is behind the chain's safe point. Without finality data it is false unless the deployment sets `COVERAGE_STALE_AFTER_SECONDS`, in which case it is true when any indexed protocol has gone that long without committing a batch, or when nothing has synced yet.""" stale: Boolean! """Per-protocol indexed positions.""" protocols: [ProtocolCoverage!]! diff --git a/src/api/api_endpoints.zig b/src/api/api_endpoints.zig index 05cf85e..3364055 100644 --- a/src/api/api_endpoints.zig +++ b/src/api/api_endpoints.zig @@ -13,6 +13,7 @@ const models = @import("../types/models.zig"); const Address = @import("../types/address.zig").Address; const Hash = @import("../types/hash.zig").Hash; const graphql = @import("handler.zig"); +const api_common = @import("common.zig"); const parser = @import("../lib/graphql/parser.zig"); const json_utils = @import("../utils/json.zig"); const url_utils = @import("../utils/url.zig"); @@ -467,32 +468,32 @@ pub fn handleHealthCheck(self: *Server, conn: http_util.Conn) !void { /// Readiness: can this node actually serve queries? Acquires a pool session and does a /// trivial read; returns 503 when the DB is unreachable so a load balancer routes traffic -/// away. Staleness (indexed head behind the safe head) is surfaced as a `stale` flag, not -/// a 503, so a node that is merely a little behind keeps serving instead of flapping out -/// of rotation. +/// away. Staleness is surfaced as a `stale` flag (api/common.coverageStale), not a 503, +/// so a node that is merely a little behind keeps serving instead of flapping out of +/// rotation. pub fn handleReadiness(self: *Server, conn: http_util.Conn) !void { const database = self.pool.acquire() catch return self.sendJsonResponse(conn, 503, "{\"status\":\"not_ready\",\"reason\":\"db_unavailable\"}"); defer self.pool.release(database); - const v1 = (database.getSyncState(.v1) catch - return self.sendJsonResponse(conn, 503, "{\"status\":\"not_ready\",\"reason\":\"db_unreachable\"}")) orelse 0; - const v2 = (database.getSyncState(.v2) catch - return self.sendJsonResponse(conn, 503, "{\"status\":\"not_ready\",\"reason\":\"db_unreachable\"}")) orelse 0; - const head: u64 = if (v1 > v2) v1 else v2; + const v1 = database.getSyncStateFull(.v1) catch + return self.sendJsonResponse(conn, 503, "{\"status\":\"not_ready\",\"reason\":\"db_unreachable\"}"); + const v2 = database.getSyncStateFull(.v2) catch + return self.sendJsonResponse(conn, 503, "{\"status\":\"not_ready\",\"reason\":\"db_unreachable\"}"); + const head = api_common.indexedHead(v1, v2); const safe = database.getFinality(database.chain_id, .safe) catch null; - const safe_num: u64 = if (safe) |sp| sp.number else 0; - const stale = safe != null and head < safe_num; + const safe_num: ?u64 = if (safe) |sp| sp.number else null; + const stale = api_common.coverageStale(v1, v2, safe_num, database.stale_after_seconds, zsys.timestamp()); - const body = try std.fmt.allocPrint(self.allocator, "{{\"status\":\"ready\",\"indexed_head\":{d},\"safe\":{d},\"stale\":{s}}}", .{ head, safe_num, if (stale) "true" else "false" }); + const body = try std.fmt.allocPrint(self.allocator, "{{\"status\":\"ready\",\"indexed_head\":{d},\"safe\":{d},\"stale\":{s}}}", .{ head, safe_num orelse 0, if (stale) "true" else "false" }); defer self.allocator.free(body); try self.sendJsonResponse(conn, 200, body); } /// Coverage declaration: chain id, per-protocol indexed head + last-sync time, and a -/// staleness flag (same semantics as /ready's `stale`: false when no finality data). -/// The GraphQL `_coverage` field serves the same data with field selection. +/// staleness flag (api/common.coverageStale, the same flag /ready reports). The +/// GraphQL `_coverage` field serves the same data with field selection. pub fn handleCoverage(self: *Server, conn: http_util.Conn) !void { const database = self.pool.acquire() catch return self.sendJsonResponse(conn, 503, "{\"status\":\"unavailable\",\"reason\":\"db_unavailable\"}"); @@ -500,16 +501,13 @@ pub fn handleCoverage(self: *Server, conn: http_util.Conn) !void { const v1 = database.getSyncStateFull(.v1) catch null; const v2 = database.getSyncStateFull(.v2) catch null; - const v1_block: u64 = if (v1) |s| s.block else 0; - const v2_block: u64 = if (v2) |s| s.block else 0; - const head: u64 = if (v1_block > v2_block) v1_block else v2_block; const safe = database.getFinality(database.chain_id, .safe) catch null; - const stale = if (safe) |sp| head < sp.number else false; + const stale = api_common.coverageStale(v1, v2, if (safe) |sp| sp.number else null, database.stale_after_seconds, zsys.timestamp()); const body = try std.fmt.allocPrint( self.allocator, "{{\"chainId\":{d},\"stale\":{s},\"protocols\":[{{\"protocol\":\"v1\",\"indexedHead\":{d},\"lastSyncedAt\":{?d}}},{{\"protocol\":\"v2\",\"indexedHead\":{d},\"lastSyncedAt\":{?d}}}]}}", - .{ database.chain_id, if (stale) "true" else "false", v1_block, if (v1) |s| s.at else null, v2_block, if (v2) |s| s.at else null }, + .{ database.chain_id, if (stale) "true" else "false", if (v1) |s| s.block else 0, if (v1) |s| s.at else null, if (v2) |s| s.block else 0, if (v2) |s| s.at else null }, ); defer self.allocator.free(body); try self.sendJsonResponse(conn, 200, body); @@ -544,22 +542,27 @@ pub fn handleMetrics(self: *Server, conn: http_util.Conn) !void { } /// Append Prometheus finality gauges (Task 09): indexed head, safe/finalized positions, -/// safe lag, and a stale flag. Reads a pool session; 0/stale when finality is unpopulated. +/// safe lag, and both stale flags. Reads a pool session; 0/stale when finality is unpopulated. fn appendFinalityMetrics(self: *Server, out: *std.Io.Writer.Allocating) !void { const database = try self.pool.acquire(); defer self.pool.release(database); - const v1 = (try database.getSyncState(.v1)) orelse 0; - const v2 = (try database.getSyncState(.v2)) orelse 0; - const head: u64 = if (v1 > v2) v1 else v2; - const safe = try database.getFinality(database.chain_id, .safe); + const v1 = try database.getSyncStateFull(.v1); + const v2 = try database.getSyncStateFull(.v2); + const safe: ?u64 = if (try database.getFinality(database.chain_id, .safe)) |s| s.number else null; const finalized = try database.getFinality(database.chain_id, .finalized); - try writeFinalityGauges(&out.writer, head, if (safe) |s| s.number else null, if (finalized) |f| f.number else null); + const coverage_stale = api_common.coverageStale(v1, v2, safe, database.stale_after_seconds, zsys.timestamp()); + try writeFinalityGauges(&out.writer, api_common.indexedHead(v1, v2), safe, if (finalized) |f| f.number else null, coverage_stale); } /// Pure Prometheus-gauge formatter for the finality metrics (Task 09). Split out of the /// DB-coupled fetch so the gauge SET and the lag math are unit-testable. `safe`/`finalized` /// are the block numbers of the chain's safe/finalized heads (null = not yet observed). -fn writeFinalityGauges(w: *std.Io.Writer, head: u64, safe: ?u64, finalized: ?u64) !void { +/// +/// Two stale gauges, deliberately different: `ensv2_indexing_stale` is the conservative +/// `_finality.isStale` (1 whenever there is no safe head to trust); +/// `ensv2_coverage_stale` is the `stale` flag /ready, /coverage and `_coverage` report, +/// including the COVERAGE_STALE_AFTER_SECONDS fallback. +fn writeFinalityGauges(w: *std.Io.Writer, head: u64, safe: ?u64, finalized: ?u64, coverage_stale: bool) !void { try w.print("# TYPE ensv2_indexed_head gauge\nensv2_indexed_head {d}\n", .{head}); try w.print("# TYPE ensv2_finality_safe gauge\nensv2_finality_safe {d}\n", .{safe orelse 0}); try w.print("# TYPE ensv2_finality_finalized gauge\nensv2_finality_finalized {d}\n", .{finalized orelse 0}); @@ -570,6 +573,7 @@ fn writeFinalityGauges(w: *std.Io.Writer, head: u64, safe: ?u64, finalized: ?u64 try w.print("# TYPE ensv2_finality_finalized_lag gauge\nensv2_finality_finalized_lag {d}\n", .{finalized_lag}); const stale: u8 = if (safe) |s| (if (head < s) @as(u8, 1) else 0) else 1; try w.print("# TYPE ensv2_indexing_stale gauge\nensv2_indexing_stale {d}\n", .{stale}); + try w.print("# TYPE ensv2_coverage_stale gauge\nensv2_coverage_stale {d}\n", .{@intFromBool(coverage_stale)}); } test "writeFinalityGauges: emits the full finality gauge set with correct lag" { @@ -577,7 +581,7 @@ test "writeFinalityGauges: emits the full finality gauge set with correct lag" { { var buf: std.Io.Writer.Allocating = .init(a); defer buf.deinit(); - try writeFinalityGauges(&buf.writer, 200, 190, 180); // head=200, safe=190, finalized=180 + try writeFinalityGauges(&buf.writer, 200, 190, 180, false); // head=200, safe=190, finalized=180 const o = buf.written(); try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_indexed_head 200\n") != null); try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_finality_safe 190\n") != null); @@ -585,16 +589,25 @@ test "writeFinalityGauges: emits the full finality gauge set with correct lag" { try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_finality_safe_lag 10\n") != null); try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_finality_finalized_lag 20\n") != null); try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_indexing_stale 0\n") != null); + try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_coverage_stale 0\n") != null); } { // No finality observed yet -> zeros, and stale=1 (we have no safe head to trust). var buf: std.Io.Writer.Allocating = .init(a); defer buf.deinit(); - try writeFinalityGauges(&buf.writer, 200, null, null); + try writeFinalityGauges(&buf.writer, 200, null, null, false); const o = buf.written(); try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_finality_safe 0\n") != null); try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_finality_safe_lag 0\n") != null); try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_indexing_stale 1\n") != null); + // The coverage flag is whatever /coverage computed, not the conservative one. + try std.testing.expect(std.mem.indexOf(u8, o, "ensv2_coverage_stale 0\n") != null); + } + { + var buf: std.Io.Writer.Allocating = .init(a); + defer buf.deinit(); + try writeFinalityGauges(&buf.writer, 200, null, null, true); + try std.testing.expect(std.mem.indexOf(u8, buf.written(), "ensv2_coverage_stale 1\n") != null); } } diff --git a/src/api/common.zig b/src/api/common.zig index 9302389..8b5fc1a 100644 --- a/src/api/common.zig +++ b/src/api/common.zig @@ -24,6 +24,87 @@ pub const DEFAULT_SKIP: i64 = 0; /// page deeper than this should use cursor (connection) pagination. pub const MAX_SKIP: i64 = 1_000_000; +// ============================================================================ +// STALENESS +// ============================================================================ + +pub const ProtocolSync = @import("../storage/sync.zig").ProtocolSync; + +pub const StalenessInputs = struct { + /// Highest block synced across protocols. + head: u64, + /// Chain `safe` position, or null when finality data was never fetched. + safe: ?u64, + /// `last_synced_at` of each protocol; null when the protocol has no + /// sync_state row, i.e. this deployment does not index it. + synced_at: []const ?i64, + /// Seconds without a committed batch before the no-finality fallback + /// trips. 0 disables the fallback. + stale_after_seconds: u32, + now: i64, +}; + +/// The `stale` flag behind /ready, /coverage, `_coverage` and the +/// `ensv2_indexing_stale` gauge. With finality data the safe-head comparison +/// is exact. Without it, and only when the fallback is armed, a deployment is +/// stale when any protocol it indexes has gone longer than the threshold +/// without committing a batch, or when no protocol has ever synced. One live +/// protocol must not mask a dead one. +/// +/// The fallback is the only wall-clock read on the read path, so it is opt-in: +/// `stale_after_seconds == 0` keeps the answer a pure function of DB state. +pub fn isStale(in: StalenessInputs) bool { + if (in.safe) |safe_num| return in.head < safe_num; + if (in.stale_after_seconds == 0) return false; + var any_synced = false; + for (in.synced_at) |maybe_at| { + const at = maybe_at orelse continue; + if (at <= 0) continue; + any_synced = true; + // A timestamp ahead of this host's clock is clock skew between the + // indexer and API hosts, not a fresh sync; it reads as age 0. + const age = @max(in.now -| at, 0); + if (age > in.stale_after_seconds) return true; + } + return !any_synced; +} + +/// Seconds a `last_synced_at` may sit ahead of this host's clock before it is +/// reported as skew rather than ordinary drift between hosts. +pub const CLOCK_SKEW_WARN_SECONDS: i64 = 60; + +var clock_skew_warned = std.atomic.Value(bool).init(false); + +/// isStale over the two protocols' sync_state rows, shared by every surface +/// that reports staleness so they cannot disagree. Warns once per process when +/// a sync timestamp is ahead of the local clock: the fallback compares the +/// indexer host's clock with this one, and skew in that direction hides a stall. +pub fn coverageStale(v1: ?ProtocolSync, v2: ?ProtocolSync, safe: ?u64, stale_after_seconds: u32, now: i64) bool { + const synced_at = [_]?i64{ if (v1) |s| s.at else null, if (v2) |s| s.at else null }; + if (stale_after_seconds != 0 and safe == null) { + for (synced_at) |maybe_at| { + const at = maybe_at orelse continue; + if (at -| now > CLOCK_SKEW_WARN_SECONDS and !clock_skew_warned.swap(true, .monotonic)) { + std.log.warn("coverage staleness: last_synced_at {d} is {d}s ahead of this host's clock; the indexer and API clocks disagree, so the no-finality stale check is unreliable", .{ at, at -| now }); + } + } + } + return isStale(.{ + .head = indexedHead(v1, v2), + .safe = safe, + .synced_at = &synced_at, + .stale_after_seconds = stale_after_seconds, + .now = now, + }); +} + +/// Highest block synced across the two protocols; 0 when neither has synced. +pub fn indexedHead(v1: ?ProtocolSync, v2: ?ProtocolSync) u64 { + const v1_block: u64 = if (v1) |s| s.block else 0; + const v2_block: u64 = if (v2) |s| s.block else 0; + return @max(v1_block, v2_block); +} + // ============================================================================ // PAGINATION // ============================================================================ @@ -388,3 +469,74 @@ test "parseOrderDirection round-trips both directions for events" { parseOrderDirection(&makeField(&none), EventOrderDir, .desc), ); } + +fn staleAt(safe: ?u64, synced_at: []const ?i64, stale_after_seconds: u32, now: i64) bool { + return isStale(.{ .head = 100, .safe = safe, .synced_at = synced_at, .stale_after_seconds = stale_after_seconds, .now = now }); +} + +test "isStale: finality data present decides on its own" { + // Head past safe: caught up. Head behind safe: stale, regardless of clock. + try testing.expect(!staleAt(100, &.{ null, null }, 0, 0)); + try testing.expect(staleAt(101, &.{ null, null }, 0, 0)); + // A fresh clock never rescues a head that is behind safe. + try testing.expect(staleAt(101, &.{ null, 1000 }, 900, 1000)); + // An old sync never overrides a head that is at safe. + try testing.expect(!staleAt(100, &.{ null, 1 }, 900, 1_000_000)); +} + +test "isStale: without finality data, a frozen head reads stale" { + // The regression this guards: no finality data used to mean `false` even + // when the indexer had not advanced in days. + const day = 86400; + try testing.expect(staleAt(null, &.{ null, 1000 }, 900, 1000 + day)); + try testing.expect(!staleAt(null, &.{ null, 1000 }, 900, 1000 + 899)); + // Exactly at the threshold is not yet stale (strict >). + try testing.expect(!staleAt(null, &.{ null, 1000 }, 900, 1000 + 900)); + try testing.expect(staleAt(null, &.{ null, 1000 }, 900, 1000 + 901)); +} + +test "isStale: a live protocol does not mask a dead one" { + // Split binaries: v1 keeps committing while v2 stopped a day ago. + try testing.expect(staleAt(null, &.{ 100_000, 100_000 - 86400 }, 900, 100_000)); + try testing.expect(staleAt(null, &.{ 100_000 - 86400, 100_000 }, 900, 100_000)); + // A protocol this deployment does not index (no row) is ignored. + try testing.expect(!staleAt(null, &.{ null, 100_000 }, 900, 100_000)); +} + +test "isStale: never synced reads stale once the fallback is armed" { + // An API pointed at a database whose indexer never started. + try testing.expect(staleAt(null, &.{ null, null }, 900, 100_000)); + try testing.expect(staleAt(null, &.{ 0, 0 }, 900, 100_000)); + // Disabled fallback keeps the old answer. + try testing.expect(!staleAt(null, &.{ null, null }, 0, 100_000)); +} + +test "isStale: disabled fallback ignores the clock" { + try testing.expect(!staleAt(null, &.{ null, 1000 }, 0, 1000 + 86400)); +} + +test "isStale: a sync timestamp ahead of the clock reads as fresh, not negative" { + try testing.expect(!staleAt(null, &.{ null, 5000 }, 900, 1000)); + // Hostile DB values cannot overflow the subtraction. + try testing.expect(!staleAt(null, &.{ null, std.math.maxInt(i64) }, 900, std.math.minInt(i64))); + try testing.expect(staleAt(null, &.{ null, 1 }, 900, std.math.maxInt(i64))); +} + +test "coverageStale: reads both protocol rows and the head they imply" { + const now: i64 = 1_700_000_000; + const fresh = ProtocolSync{ .block = 50, .at = now }; + const dead = ProtocolSync{ .block = 40, .at = now - 86400 }; + try testing.expect(!coverageStale(null, fresh, null, 900, now)); + try testing.expect(coverageStale(dead, fresh, null, 900, now)); + try testing.expect(coverageStale(null, null, null, 900, now)); + try testing.expect(!coverageStale(null, null, null, 0, now)); + // Head is max(v1, v2): 50 is behind safe 60, and at safe 50 it is not. + try testing.expect(coverageStale(dead, fresh, 60, 0, now)); + try testing.expect(!coverageStale(dead, fresh, 50, 900, now)); +} + +test "indexedHead: highest protocol wins, absent reads as 0" { + try testing.expectEqual(@as(u64, 0), indexedHead(null, null)); + try testing.expectEqual(@as(u64, 7), indexedHead(.{ .block = 7, .at = 1 }, null)); + try testing.expectEqual(@as(u64, 9), indexedHead(.{ .block = 7, .at = 1 }, .{ .block = 9, .at = 1 })); +} diff --git a/src/api/resolvers/admin.zig b/src/api/resolvers/admin.zig index 4444e25..1f38b8f 100644 --- a/src/api/resolvers/admin.zig +++ b/src/api/resolvers/admin.zig @@ -2096,21 +2096,17 @@ pub fn resolveFinality(ctx: parser.ExecutionContext, field: *const parser.Field) /// `_coverage`: what this deployment indexes — chain id, per-protocol indexed head + /// freshness, and a staleness flag. Additive; does not touch the subgraph `_meta` shape. -/// `stale` deliberately uses /ready's convention (false when finality data is absent) -/// rather than `_finality.isStale`'s conservative true — a default deployment without -/// FINALITY_ENABLED must not permanently declare itself stale on a coverage surface. +/// `stale` is api/common.coverageStale, shared with /ready, /coverage and /metrics — +/// not `_finality.isStale`, which is true whenever there is no safe data. pub fn resolveCoverage(ctx: parser.ExecutionContext, field: *const parser.Field) !parser.FieldResult { const allocator = ctx.allocator; const database: *db.Database = @ptrCast(@alignCast(ctx.database)); const v1 = try database.getSyncStateFull(.v1); const v2 = try database.getSyncStateFull(.v2); - const v1_block: u64 = if (v1) |s| s.block else 0; - const v2_block: u64 = if (v2) |s| s.block else 0; - const head: u64 = if (v1_block > v2_block) v1_block else v2_block; // Same degrade-to-null as resolveFinality: absent finality_state = no signal. const safe = database.getFinality(database.chain_id, .safe) catch null; - const is_stale = if (safe) |snap| head < snap.number else false; + const is_stale = common.coverageStale(v1, v2, if (safe) |snap| snap.number else null, database.stale_after_seconds, common.zsys.timestamp()); var json: std.Io.Writer.Allocating = .init(allocator); defer json.deinit(); diff --git a/src/api/resolvers/common.zig b/src/api/resolvers/common.zig index 37c51e3..6c55c5b 100644 --- a/src/api/resolvers/common.zig +++ b/src/api/resolvers/common.zig @@ -16,12 +16,14 @@ pub const pagination = @import("../../lib/graphql/pagination.zig"); // builders/builders.zig. Files needing the builder layer (or `builders.NestedContext`) // should import `../builders/builders.zig` directly. pub const loaders = @import("../loaders.zig"); +pub const zsys = @import("../../utils/system.zig"); // Re-export shared helpers/constants from the neutral api/common.zig so resolver // files can access them via the same `common.*` namespace. const api_common = @import("../common.zig"); pub const parsePagination = api_common.parsePagination; pub const parseOrderDirection = api_common.parseOrderDirection; +pub const coverageStale = api_common.coverageStale; pub const parseEventOrderBy = api_common.parseEventOrderBy; pub const getObjectArg = api_common.getObjectArg; pub const matchStringArg = api_common.matchStringArg; diff --git a/src/api_main.zig b/src/api_main.zig index 772fc4b..c33e4a2 100644 --- a/src/api_main.zig +++ b/src/api_main.zig @@ -75,6 +75,7 @@ pub fn main(init: std.process.Init) !void { .database_url = cfg.database_url, .size = cfg.database_pool_size, .chain_id = cfg.network.chainId(), + .stale_after_seconds = cfg.coverage_stale_after_seconds, }); defer db_pool.deinit(); diff --git a/src/config.zig b/src/config.zig index 28b2ba0..554ee99 100644 --- a/src/config.zig +++ b/src/config.zig @@ -122,6 +122,10 @@ pub const Config = struct { /// indexer poll loop (Task 09). Off by default. The additive `_finality` API field is /// always present but returns nulls until this is on and positions are fetched. finality_enabled: bool, + /// Seconds a protocol may go without committing a batch before the coverage + /// `stale` flag trips on a deployment with no finality data. 0 (the default) + /// disables the fallback; see parseStaleAfterSeconds. + coverage_stale_after_seconds: u32, pub fn fromEnv(allocator: std.mem.Allocator) !Config { var env_map = try env_mod.loadEnv(allocator, ".env"); @@ -258,6 +262,13 @@ pub const Config = struct { .ccip_gateway_timeout_ms = env_mod.getEnvInt(&env_map, u32, "CCIP_GATEWAY_TIMEOUT_MS", 5000), .ccip_max_redirects = env_mod.getEnvInt(&env_map, u32, "CCIP_MAX_REDIRECTS", 4), .finality_enabled = env_mod.getEnvBool(&env_map, "FINALITY_ENABLED", false), + .coverage_stale_after_seconds = blk: { + const raw = env_mod.getEnv(&env_map, "COVERAGE_STALE_AFTER_SECONDS", ""); + break :blk parseStaleAfterSeconds(raw) orelse { + std.log.warn("Invalid COVERAGE_STALE_AFTER_SECONDS '{s}' (want whole seconds, or 0/off to disable); the no-finality stale check is OFF", .{raw}); + break :blk 0; + }; + }, }; } @@ -296,6 +307,30 @@ pub const Config = struct { } }; +/// COVERAGE_STALE_AFTER_SECONDS: whole seconds, or empty / `0` / `off` / +/// `false` / `no` to disable. Null for anything else, so a typo is reported +/// instead of silently picking a threshold. +pub fn parseStaleAfterSeconds(raw: []const u8) ?u32 { + const value = std.mem.trim(u8, raw, " \t"); + if (value.len == 0) return 0; + for ([_][]const u8{ "off", "false", "no" }) |word| { + if (std.ascii.eqlIgnoreCase(value, word)) return 0; + } + return std.fmt.parseInt(u32, value, 10) catch null; +} + +test "parseStaleAfterSeconds: unset and the off spellings disable, seconds pass through, junk is rejected" { + try std.testing.expectEqual(@as(?u32, 0), parseStaleAfterSeconds("")); + try std.testing.expectEqual(@as(?u32, 0), parseStaleAfterSeconds("0")); + try std.testing.expectEqual(@as(?u32, 0), parseStaleAfterSeconds("off")); + try std.testing.expectEqual(@as(?u32, 0), parseStaleAfterSeconds("OFF")); + try std.testing.expectEqual(@as(?u32, 0), parseStaleAfterSeconds("false")); + try std.testing.expectEqual(@as(?u32, 3600), parseStaleAfterSeconds("3600")); + try std.testing.expectEqual(@as(?u32, 3600), parseStaleAfterSeconds(" 3600 ")); + try std.testing.expectEqual(@as(?u32, null), parseStaleAfterSeconds("1h")); + try std.testing.expectEqual(@as(?u32, null), parseStaleAfterSeconds("-5")); +} + test "validateResolution: CCIP without live is a hard error; both-off / both-on / live-only are OK" { var c: Config = undefined; c.resolve_ccip_enabled = true; diff --git a/src/storage/database.zig b/src/storage/database.zig index bae81a2..8f2b5d8 100644 --- a/src/storage/database.zig +++ b/src/storage/database.zig @@ -117,6 +117,11 @@ pub const Database = struct { /// still overrides inside dropSyncIndexes. Paths that never bulk-sync /// (API, tools, tests) keep the default. sync_cache_mb: u64 = 512, + /// COVERAGE_STALE_AFTER_SECONDS: how long a protocol may go without + /// committing a batch before the coverage `stale` flag trips on a deployment + /// with no finality data. Set by the API pool from Config; 0 (off) keeps + /// `stale` a pure function of DB state. + stale_after_seconds: u32 = 0, /// Records the chain ID this database serves data for. The value flows /// into Resolver entity IDs at JSON-build time. Called by both the @@ -125,6 +130,11 @@ pub const Database = struct { self.chain_id = chain_id; } + /// Arms the no-finality staleness fallback for the coverage surface. + pub fn setStaleAfterSeconds(self: *Database, seconds: u32) void { + self.stale_after_seconds = seconds; + } + // ======================================================================== // CORE FUNCTIONS (kept in this file) // ======================================================================== diff --git a/src/storage/pool.zig b/src/storage/pool.zig index 1b7eeb8..efc2ec8 100644 --- a/src/storage/pool.zig +++ b/src/storage/pool.zig @@ -37,6 +37,9 @@ pub const Options = struct { size: u32 = 10, /// EIP-155 chain id, set on every session (entity-ID formatting). chain_id: u64 = 0, + /// COVERAGE_STALE_AFTER_SECONDS, set on every session. 0 leaves the + /// no-finality stale fallback off. + stale_after_seconds: u32 = 0, }; pub const Pool = struct { @@ -76,6 +79,7 @@ pub const Pool = struct { .backend = try db_open.selectBackend(allocator, opts.kind, opts.sqlite_path, opts.database_url), }; s.setChainId(opts.chain_id); + s.setStaleAfterSeconds(opts.stale_after_seconds); sessions[opened] = s; opened += 1; } diff --git a/tests/conformance/runner.zig b/tests/conformance/runner.zig index 9d16b41..e70ab2c 100644 --- a/tests/conformance/runner.zig +++ b/tests/conformance/runner.zig @@ -602,6 +602,61 @@ test "task06: indexed-miss addr resolves via Universal Resolver only when live i try testing.expect(std.mem.indexOf(u8, gated_on, "0x3333333333333333333333333333333333333333") == null); } +// ============================================================================ +// `_coverage.stale` with the no-finality fallback armed. Not a golden: the +// fallback reads the wall clock, so timestamps are pinned relative to it. +// ============================================================================ + +fn coverageStaleFlag(a: std.mem.Allocator, handler: *GraphQLHandler, db: *Database) !bool { + const result = try handler.handleQuery(db, "{ _coverage { stale } }", null, null, false); + defer a.free(result); + if (std.mem.eql(u8, result, "{\"data\":{\"_coverage\":{\"stale\":true}}}")) return true; + if (std.mem.eql(u8, result, "{\"data\":{\"_coverage\":{\"stale\":false}}}")) return false; + std.debug.print("unexpected _coverage response: {s}\n", .{result}); + return error.UnexpectedCoverageResponse; +} + +fn pinSyncState(db: *Database, protocol: []const u8, block: u64, at: i64) !void { + var q = try lib.storage.Query.init(db, "INSERT INTO sync_state (protocol, last_synced_block, last_synced_at) VALUES (?, ?, ?) ON CONFLICT (protocol) DO UPDATE SET last_synced_block = excluded.last_synced_block, last_synced_at = excluded.last_synced_at"); + defer q.deinit(); + try q.bindTextStatic(protocol); + try q.bindInt64(@intCast(block)); + try q.bindInt64(at); + try q.exec(); +} + +test "_coverage.stale: no-finality fallback over the real handler" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const db = try helpers.createTestDatabase(a); + defer helpers.destroyTestDatabase(a, db); + var handler = try GraphQLHandler.init(a, 30, 100000, false); + defer handler.deinit(); + + // Fallback off (the default): nothing synced, nothing stale. + try testing.expect(!try coverageStaleFlag(a, &handler, db)); + + db.setStaleAfterSeconds(900); + // Armed, and the indexer never started. + try testing.expect(try coverageStaleFlag(a, &handler, db)); + + const now = zsys.timestamp(); + try pinSyncState(db, "v2", 100, now); + try testing.expect(!try coverageStaleFlag(a, &handler, db)); + + // v1 keeps committing, v2 stopped a day ago: v1 must not mask it. + try pinSyncState(db, "v1", 100, now); + try pinSyncState(db, "v2", 100, now - 86400); + try testing.expect(try coverageStaleFlag(a, &handler, db)); + + // Finality data wins over the clock both ways. + try db.setFinality(db.chain_id, .safe, 100, Hash.zero, now); + try testing.expect(!try coverageStaleFlag(a, &handler, db)); + try db.setFinality(db.chain_id, .safe, 101, Hash.zero, now); + try testing.expect(try coverageStaleFlag(a, &handler, db)); +} + // ============================================================================ // Record-model resolvers (contracts-v2 IRecordResolver) — own fixture so the // main goldens above stay byte-identical. diff --git a/tests/storage/pool_test.zig b/tests/storage/pool_test.zig index c51ef1d..49463f3 100644 --- a/tests/storage/pool_test.zig +++ b/tests/storage/pool_test.zig @@ -223,3 +223,19 @@ const ThreadSafeAllocator = struct { return self.child_allocator.rawFree(buf, alignment, ra); } }; + +test "pool arms the coverage stale threshold on every session" { + const file = "/tmp/zigens_pool_stale_after.db"; + defer cleanupSqliteFile(file); + + var opts = fileOptions(2, file); + opts.stale_after_seconds = 3600; + var pool = try Pool.open(testing.allocator, opts); + defer pool.deinit(); + + for (pool.sessions) |s| try testing.expectEqual(@as(u32, 3600), s.stale_after_seconds); + + var off = try Pool.open(testing.allocator, .{ .kind = .sqlite, .sqlite_path = ":memory:", .size = 1, .chain_id = 1 }); + defer off.deinit(); + try testing.expectEqual(@as(u32, 0), off.sessions[0].stale_after_seconds); +} diff --git a/tests/storage/postgres_driver_test.zig b/tests/storage/postgres_driver_test.zig index 26bc46e..ac9dcb5 100644 --- a/tests/storage/postgres_driver_test.zig +++ b/tests/storage/postgres_driver_test.zig @@ -70,6 +70,7 @@ fn pgTestConfig() !config.Config { .ccip_gateway_timeout_ms = 5000, .ccip_max_redirects = 4, .finality_enabled = false, + .coverage_stale_after_seconds = 0, }; } From 0202bc6a3172971b4d3d0ebf25aec4a9e5b7c83d Mon Sep 17 00:00:00 2001 From: v1rtl Date: Tue, 29 Sep 2026 15:36:31 +0200 Subject: [PATCH 2/2] chore(deploy): arm the no-finality stale check in the compose files The code default stays off. The deployments we run opt in at 3600s, above the longest healthy batch on record, overridable per host. --- docker-compose.server.yml | 4 ++++ docker-compose.staging.yml | 4 ++++ docker-compose.yml | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/docker-compose.server.yml b/docker-compose.server.yml index d1cba60..773a55d 100644 --- a/docker-compose.server.yml +++ b/docker-compose.server.yml @@ -74,6 +74,10 @@ services: - API_PORT=5655 - GRAPHQL_MAX_DEPTH=10 - GRAPHQL_MAX_COST=${GRAPHQL_MAX_COST:-10000} + # Without finality data, report stale=true once a protocol has gone this long + # without committing a batch (see .env.example). Above the longest healthy + # batch; set 0 for a --backfill or an END_BLOCK-pinned deployment. + - COVERAGE_STALE_AFTER_SECONDS=${COVERAGE_STALE_AFTER_SECONDS:-3600} - WEBHOOKS_ENABLED=${WEBHOOKS_ENABLED:-false} - WEBHOOK_DB_PATH=/app/webhooks/webhooks.db - WEBHOOK_ADMIN_USERNAME=${WEBHOOK_ADMIN_USERNAME:-} diff --git a/docker-compose.staging.yml b/docker-compose.staging.yml index 9285c8f..29e35df 100644 --- a/docker-compose.staging.yml +++ b/docker-compose.staging.yml @@ -137,6 +137,10 @@ services: # throttle, so setting it only there left the API on the code default (15/s) # and capped the public surface without anyone choosing that number. - RATE_LIMIT_PER_SECOND=${API_RATE_LIMIT_PER_SECOND:-25} + # Without finality data, report stale=true once a protocol has gone this long + # without committing a batch (see .env.example). Above the longest healthy + # batch; set 0 for a --backfill or an END_BLOCK-pinned deployment. + - COVERAGE_STALE_AFTER_SECONDS=${COVERAGE_STALE_AFTER_SECONDS:-3600} - GRAPHQL_MAX_DEPTH=10 - GRAPHQL_MAX_COST=${GRAPHQL_MAX_COST:-10000} # Live resolution (ENSIP-10 Universal Resolver fallback) for single-name diff --git a/docker-compose.yml b/docker-compose.yml index 256a009..657df6d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -96,6 +96,10 @@ services: # throttle, so setting it only there left the API on the code default (15/s) # and capped the public surface without anyone choosing that number. - RATE_LIMIT_PER_SECOND=${API_RATE_LIMIT_PER_SECOND:-25} + # Without finality data, report stale=true once a protocol has gone this long + # without committing a batch (see .env.example). Above the longest healthy + # batch; set 0 for a --backfill or an END_BLOCK-pinned deployment. + - COVERAGE_STALE_AFTER_SECONDS=${COVERAGE_STALE_AFTER_SECONDS:-3600} # Number of trusted reverse-proxy hops. MUST be non-zero behind a proxy: # at 0 the limiter keys on the direct TCP peer, which is the proxy, so every # client on earth shares one bucket. Count the real chain (CDN -> ingress ->