Add per-chain effect caching and rate limiting - #1432
Conversation
Add a `crossChain` option to the Effect API (defaults to `true`). When `crossChain: false`, an effect's cache and rate-limit window are isolated per chain and the handler can read `context.chain.id`. - Public API: `crossChain?: boolean` on effect options; required `context.chain.id` in ReScript and TypeScript types. Reading `context.chain` on a cross-chain effect throws a guiding error. - Scope model (`CrossChain | Chain(int)`) resolved from the effect config and the current handler chain. Nested calls follow: handler -> either; chain -> either; cross-chain -> cross-chain; cross-chain -> chain fails before cache lookup with both effect names and remediation. - Per-scope runtime boundary: in-memory cache, in-flight dedup, rate-limit window/queue and active-call state are keyed by the resolved cache address; the canonical input key is unchanged. - Central reversible mapping `Internal.EffectCache` between (effectName, scope) <-> table name <-> cache file path, used everywhere instead of prefix slicing. Cache metadata is keyed by the full address. - Postgres: cross-chain tables `envio_effect_<name>`, chain-scoped `envio_<chainId>_effect_<name>`; discovery matches both formats. `.envio/cache` gains numeric per-chain subdirectories; restore rejects malformed chain directories and supports one directory level; dump does the exact reverse mapping. Tests: address round trips / legacy / coexistence / invalid parsing, per-chain dedup and independent rate limits, cross-chain sharing, and an E2E covering context.chain.id, the guiding errors, and per-chain persistence. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
…t error tests Address review feedback: - Make `context.chain` an enumerable own getter closing over the resolved chain, dropping the hidden `_chainId`/`_effectName` instance fields. - Mark `effectScope` `@unboxed` (CrossChain -> "crossChain", Chain(id) -> the raw id, discriminated by runtime type). - Assert the exact cross-chain `context.chain` and nested cross-chain -> chain-scoped error messages in the E2E test. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
…e write path, prototype getter - Rename `effectScope` -> `chainScope` (generic; reused for entities later). - Persistence write path no longer threads effect+scope: `updatedEffectCache` and `setEffectCacheOrThrow` take the resolved `table` (the cache address) + item schema. The in-mem table now holds its built `table`, so the address is resolved once in `getEffectInMemTable` and reused by load/snapshot/write. - Move the `context.chain` getter back onto the prototype (enumerable, like `log`), reading per-instance non-enumerable fields. - Collapse the two MockIndexer cache-query helpers into one `queryEffectCache(effect, ~scope=?)`. - Tighten the crossChain docs: concise and user-facing, no table/file internals. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
|
Warning Review limit reachedYou’ve reached a temporary PR review limit under our Fair Usage Limits Policy. Next review available in: 18 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (5)
📝 WalkthroughWalkthroughEffects gain optional chain scoping, with chain-aware context, cache tables and files, rate limiting, persistence, Prometheus labels, nested-call validation, and integration coverage for cross-chain and per-chain behavior. ChangesChain-scoped effects
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant Handler
participant UserContext
participant LoadLayer
participant EffectState
participant PostgreSQL
Handler->>UserContext: invoke effect with chain context
UserContext->>UserContext: resolve CrossChain or Chain(id)
UserContext->>LoadLayer: loadEffect(effect, scope)
LoadLayer->>EffectState: getTable(effect, scope)
EffectState->>PostgreSQL: read scoped cache table
PostgreSQL-->>EffectState: cached effect output
EffectState-->>LoadLayer: scoped table result
LoadLayer-->>UserContext: effect result
UserContext-->>Handler: result and context.chain when enabled
Possibly related issues
Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f71e0a59a6
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| Prometheus.EffectCalls.activeCallsCount->Prometheus.SafeGauge.handleInt( | ||
| ~labels=effectName, | ||
| ~value=effect.activeCallsCount, | ||
| ~value=inMemTable.activeCallsCount, |
There was a problem hiding this comment.
Aggregate active effect counts across chain scopes
When a chain-scoped effect runs concurrently on multiple chains, each chain now has a separate inMemTable with its own activeCallsCount, but all scopes still write the gauge under the same {effect} label. For example, two active calls on chains 1 and 2 both set envio_effect_active_calls{effect=...} to 1, and the first one to finish sets it to 0 while the other call is still running. Please either aggregate the count across the effect's scopes before setting this gauge or include the scope/chain in the metric labels.
Useful? React with 👍 / 👎.
| | None => | ||
| let c: Persistence.effectCacheRecord = {effectName, count: 0} | ||
| cache->Dict.set(effectName, c) | ||
| let c: Persistence.effectCacheRecord = {effectName, scope, tableName, count: 0} |
There was a problem hiding this comment.
Aggregate effect-cache counts across chain scopes
When the same chain-scoped effect has cached rows on more than one chain, this now creates one cache record per table, but envio_effect_cache is still set later with only the effect name as its label. A two-chain effect with 5 cached rows on chain 1 and 7 on chain 2 will report whichever table was snapshotted/resumed last instead of the total (or a scoped value), making the cache metric misleading. Please either sum records for the same effect before setting the gauge or add the scope/chain to the metric labels.
Useful? React with 👍 / 👎.
| | CrossChain => effectName ++ ".tsv" | ||
| | Chain(chainId) => `${chainId->Int.toString}/${effectName}.tsv` |
There was a problem hiding this comment.
Escape effect names in cache file paths
When an effect name contains a path separator, the new cache path mapping is not reversible: a cross-chain effect named 1/foo dumps to .envio/cache/1/foo.tsv, and scanCacheDir() later restores that file as the chain-scoped cache for effect foo on chain 1. Since createEffect accepts an arbitrary string name and there is no validation here, dumped caches can be silently lost or attached to a different effect/scope. Please encode or validate effect names before using them as path segments.
Useful? React with 👍 / 👎.
| WHERE t.table_schema = '${pgSchema}' | ||
| AND t.table_name LIKE '${Internal.cacheTablePrefix}%';` | ||
| WHERE t.table_schema = '${pgSchema}' | ||
| AND t.table_name ~ '^envio_([0-9]+_)?effect_.+';` |
There was a problem hiding this comment.
Exclude user tables from cache discovery
If a user's schema has an entity table whose name matches the new chain-cache pattern, such as envio_1_effect_Foo, this query treats that entity table as an effect cache table. On resume/dump it is recorded as the cache for effect Foo on chain 1, and a real chain-scoped effect with that name can then try to load or write id/output cache rows against the entity table instead of initializing its own cache table. Please filter by the cache table schema/columns or reserve and reject this table-name namespace for entities.
Useful? React with 👍 / 👎.
#1435) The envio_effect_active_calls, envio_effect_cache, and envio_effect_queue gauges are backed by per-scope state since caching became chain-scoped, so scopes of the same effect clobbered each other's value. Label them with scope: "crossChain" | <chain id>. Cache directory chain ids are now parsed strictly: "1foo" and "007" are rejected instead of being treated as chains 1 and 7 via parseInt semantics. Claude-Session: https://claude.ai/code/session_011YLPufR6wf9LYFAsNjKz1t Co-authored-by: Claude <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/envio/src/UserContext.res (1)
30-59: 📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy liftMove
_chainIdand_effectNameout of%%raw.These fields have known shapes, but raw JavaScript bypasses ReScript’s type checker. Define a private typed backing object and install the getter through typed bindings or
Utils.Object.defineProperty.As per coding guidelines,
**/*.res: “Never use%rawto access object fields if you know the type.”🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/envio/src/UserContext.res` around lines 30 - 59, Move the `_chainId` and `_effectName` field definitions out of the `%%raw` block in `UserContext`, introducing a private typed backing object for these known fields. Install the `chain` getter and initialize the fields through typed bindings or `Utils.Object.defineProperty`, while preserving the existing cross-chain error and `context.chain.id` behavior; keep only unavoidable raw construction logic.Source: Coding guidelines
🧹 Nitpick comments (2)
packages/envio/src/Persistence.res (1)
48-50: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove implementation-narration comments. Both comments restate the code’s data flow rather than documenting a surprising constraint or invariant.
packages/envio/src/Persistence.res#L48-L50: remove the “rather than an effect + scope” refactor narration.packages/envio/src/PgStorage.res#L1577-L1578: remove the reverse-mapping/subdirectory narration.As per coding guidelines, “Don't write a comment that restates what the code already says” and “Never narrate the refactor itself.”
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/envio/src/Persistence.res` around lines 48 - 50, Remove the implementation-narration comment at packages/envio/src/Persistence.res lines 48-50, including its explanation of the resolved table versus effect and scope. Also remove the reverse-mapping/subdirectory narration at packages/envio/src/PgStorage.res lines 1577-1578; no code changes are needed at either site.Source: Coding guidelines
scenarios/test_codegen/test/E2E_test.res (1)
610-633: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCapture expected exceptions with expressions, not mutable error refs.
Compute both messages with
try { await ...; "" } catch { ... }inside the handler instead of mutatingcrossChainAccessErrorandnestedError.As per coding guidelines,
**/*.res: “Use try/catch as expressions instead of refs for tracking success/failure.”🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@scenarios/test_codegen/test/E2E_test.res` around lines 610 - 633, Update the handler passed to sourceMock.resolveGetItemsOrThrow so crossChainAccessError and nestedError are assigned directly from try/catch expressions around their respective context.effect calls. Preserve the current behavior of returning an empty string on success and msgOf(exn) when an exception is caught, and remove the mutable error refs and mutation assignments.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/envio/src/Internal.res`:
- Around line 779-850: Update EffectCache.toTableName and
EffectCache.toCachePath to reject negative Chain values before encoding cache
table names or cache paths, preserving reversible canonical addressing; in
scenarios/test_codegen/test/lib_tests/EffectCache_test.res lines 55-63, add
assertions that both encoders reject Chain(-1).
In `@packages/envio/src/PgStorage.res`:
- Around line 1271-1274: The cache filename handling in restoreEffectCache must
treat both nested and flat cache names as untrusted input. At
packages/envio/src/PgStorage.res lines 1271-1274 and 1287-1289, validate each
filename against one canonical safe format before deriving effectName,
constructing Internal.makeCacheTable, or joining paths; also ensure downstream
restoration quotes SQL identifiers and uses structured process/file APIs instead
of shell redirection.
In `@scenarios/test_codegen/test/LoadLayer_test.res`:
- Around line 948-959: Update the assertion in this chain-isolation test to
verify that “chain2-a” appears before “chain1-b” in the recorded order, rather
than requiring “chain2-a” to be the first completion. Preserve the existing
assertion that all three handlers ran.
---
Outside diff comments:
In `@packages/envio/src/UserContext.res`:
- Around line 30-59: Move the `_chainId` and `_effectName` field definitions out
of the `%%raw` block in `UserContext`, introducing a private typed backing
object for these known fields. Install the `chain` getter and initialize the
fields through typed bindings or `Utils.Object.defineProperty`, while preserving
the existing cross-chain error and `context.chain.id` behavior; keep only
unavoidable raw construction logic.
---
Nitpick comments:
In `@packages/envio/src/Persistence.res`:
- Around line 48-50: Remove the implementation-narration comment at
packages/envio/src/Persistence.res lines 48-50, including its explanation of the
resolved table versus effect and scope. Also remove the
reverse-mapping/subdirectory narration at packages/envio/src/PgStorage.res lines
1577-1578; no code changes are needed at either site.
In `@scenarios/test_codegen/test/E2E_test.res`:
- Around line 610-633: Update the handler passed to
sourceMock.resolveGetItemsOrThrow so crossChainAccessError and nestedError are
assigned directly from try/catch expressions around their respective
context.effect calls. Preserve the current behavior of returning an empty string
on success and msgOf(exn) when an exception is caught, and remove the mutable
error refs and mutation assignments.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 22d757cc-18b6-4f64-a44a-d0661e062897
📒 Files selected for processing (20)
packages/cli/templates/static/shared/.claude/skills/indexer-external-calls/SKILL.mdpackages/envio/index.d.tspackages/envio/src/Envio.respackages/envio/src/InMemoryStore.respackages/envio/src/IndexerState.respackages/envio/src/IndexerState.resipackages/envio/src/Internal.respackages/envio/src/LoadLayer.respackages/envio/src/LoadLayer.resipackages/envio/src/Persistence.respackages/envio/src/PgStorage.respackages/envio/src/Prometheus.respackages/envio/src/UserContext.respackages/envio/src/Writing.respackages/envio/src/bindings/NodeJs.resscenarios/test_codegen/src/handlers/EventHandlers.tsscenarios/test_codegen/test/E2E_test.resscenarios/test_codegen/test/LoadLayer_test.resscenarios/test_codegen/test/helpers/MockIndexer.resscenarios/test_codegen/test/lib_tests/EffectCache_test.res
| type chainScope = | ||
| | @as("crossChain") CrossChain | ||
| | Chain(int) | ||
|
|
||
| let cacheTablePrefix = "envio_effect_" | ||
|
|
||
| // The single reversible mapping between an effect's (name, scope) and its | ||
| // canonical Postgres cache-table name and .envio/cache file path. Everything | ||
| // that needs a cache address goes through here instead of slicing prefixes. | ||
| // CrossChain -> envio_effect_<name> <name>.tsv | ||
| // Chain(1) -> envio_1_effect_<name> 1/<name>.tsv | ||
| // Chain(137) -> envio_137_effect_<name> 137/<name>.tsv | ||
| module EffectCache = { | ||
| let toTableName = (~effectName, ~scope) => | ||
| switch scope { | ||
| | CrossChain => cacheTablePrefix ++ effectName | ||
| | Chain(chainId) => `envio_${chainId->Int.toString}_effect_${effectName}` | ||
| } | ||
|
|
||
| // "crossChain" or the decimal chain id. Used as the `scope` Prometheus label. | ||
| let scopeToString = scope => | ||
| switch scope { | ||
| | CrossChain => "crossChain" | ||
| | Chain(chainId) => chainId->Int.toString | ||
| } | ||
|
|
||
| // Only accepts a canonical decimal chain id ("7", not "007" or "1foo") — | ||
| // Int.fromString alone follows parseInt semantics and accepts both. | ||
| let parseChainId = str => | ||
| switch Int.fromString(str) { | ||
| | Some(chainId) if chainId >= 0 && chainId->Int.toString === str => Some(chainId) | ||
| | _ => None | ||
| } | ||
|
|
||
| let chainScopedRe = /^envio_([0-9]+)_effect_(.+)$/ | ||
| let crossChainRe = /^envio_effect_(.+)$/ | ||
|
|
||
| // Inverse of toTableName. Returns None for any table name that isn't a cache | ||
| // table. Chain-scoped is tried first: the `_effect_` separator keeps effect | ||
| // names that themselves start with digits unambiguous. | ||
| let fromTableName = (tableName): option<(string, chainScope)> => | ||
| switch RegExp.exec(chainScopedRe, tableName) { | ||
| | Some(result) => | ||
| switch ( | ||
| RegExp.Result.matches(result)->Array.get(0), | ||
| RegExp.Result.matches(result)->Array.get(1), | ||
| ) { | ||
| | (Some(Some(chainIdStr)), Some(Some(effectName))) => | ||
| switch parseChainId(chainIdStr) { | ||
| | Some(chainId) => Some((effectName, Chain(chainId))) | ||
| | None => None | ||
| } | ||
| | _ => None | ||
| } | ||
| | None => | ||
| switch RegExp.exec(crossChainRe, tableName) { | ||
| | Some(result) => | ||
| switch RegExp.Result.matches(result)->Array.get(0) { | ||
| | Some(Some(effectName)) => Some((effectName, CrossChain)) | ||
| | _ => None | ||
| } | ||
| | None => None | ||
| } | ||
| } | ||
|
|
||
| // Relative posix path within .envio/cache. Chain-scoped caches live one | ||
| // directory level deep, named by chain id. | ||
| let toCachePath = (~effectName, ~scope) => | ||
| switch scope { | ||
| | CrossChain => effectName ++ ".tsv" | ||
| | Chain(chainId) => `${chainId->Int.toString}/${effectName}.tsv` | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
Validate chain IDs before encoding cache addresses.
chainScope permits negative integers, but the decoder intentionally accepts only canonical non-negative IDs, making the mapping non-reversible.
packages/envio/src/Internal.res#L779-L850: reject negativeChainvalues before producing table names or cache paths.scenarios/test_codegen/test/lib_tests/EffectCache_test.res#L55-L63: assert that both address encoders rejectChain(-1).
📍 Affects 2 files
packages/envio/src/Internal.res#L779-L850(this comment)scenarios/test_codegen/test/lib_tests/EffectCache_test.res#L55-L63
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/envio/src/Internal.res` around lines 779 - 850, Update
EffectCache.toTableName and EffectCache.toCachePath to reject negative Chain
values before encoding cache table names or cache paths, preserving reversible
canonical addressing; in
scenarios/test_codegen/test/lib_tests/EffectCache_test.res lines 55-63, add
assertions that both encoders reject Chain(-1).
…y columns Two review points not covered by #1435: - Validate effect names to `[A-Za-z0-9_-]+` in createEffect. The name is used as a cache table name and a .envio/cache path segment, so path separators and traversal (`a/b`, `../evil`) must be rejected to keep the (name, scope) <-> table <-> path mapping reversible. - Cache-table discovery now also requires the effect-cache column shape (exactly `id` + `output`), so a user entity table that matches the reserved name pattern is never mistaken for an effect cache. #1435 already addressed the per-scope metric-gauge clobbering (via a scope label) and strict chain-id parsing, so those are not duplicated here. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 095b8fc28d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| AND ( | ||
| SELECT array_agg(c.column_name::text ORDER BY c.column_name::text) | ||
| FROM information_schema.columns c | ||
| WHERE c.table_schema = t.table_schema AND c.table_name = t.table_name | ||
| ) = ARRAY['id', 'output'];` |
There was a problem hiding this comment.
Exclude id/output entity tables from cache discovery
For a user entity table named envio_1_effect_Foo or envio_effect_Foo with exactly id and output fields, this discovery query still classifies the entity as an effect cache because the guard only compares column names. On resume/dump it will be recorded as the cache for effect Foo, and a matching effect can read or upsert cache rows through the user entity table, misparsing or corrupting user data. Fresh evidence: the new guard here is only ARRAY['id', 'output'], not a reserved namespace check or a type/schema check.
Useful? React with 👍 / 👎.
| rateLimitState: switch effect.rateLimit { | ||
| | None => None | ||
| | Some({callsPerDuration, durationMs}) => | ||
| Some({ | ||
| callsPerDuration, | ||
| durationMs, | ||
| availableCalls: callsPerDuration, | ||
| windowStartTime: Date.now(), | ||
| queueCount: 0, | ||
| nextWindowPromise: None, | ||
| }) | ||
| }, |
There was a problem hiding this comment.
Preserve rate-limit state across rollbacks
When a reorg triggers IndexerState.beginRollbackDiff, it clears state.effects; since this change initializes rateLimitState inside each effect cache table, the next replayed effect call creates a fresh table with a full budget. For example, an effect limited to 1 call per minute can run once, hit a rollback immediately, and then run again during replay without waiting, whereas the previous effect-level state survived the rollback reset. Please keep the rate-limit window outside the cache table state or carry it across the rollback reset.
Useful? React with 👍 / 👎.
| let toTableName = (~effectName, ~scope) => | ||
| switch scope { | ||
| | CrossChain => cacheTablePrefix ++ effectName | ||
| | Chain(chainId) => `envio_${chainId->Int.toString}_effect_${effectName}` |
There was a problem hiding this comment.
Bound chain-scoped cache table names
For chain-scoped effects with long but otherwise valid names, this extra envio_<chain>_effect_ prefix can push the quoted PostgreSQL identifier past the 63-byte limit; e.g. a 49-character name on chain 1 is 64 bytes here even though the old cross-chain table name fit. PostgreSQL silently truncates identifiers, so cache discovery resumes under the truncated name while loadEffect looks up the untruncated tableName, losing the persisted cache and allowing collisions between effects that differ only after the truncation point. Please validate the full scoped table name length or use a shortened/hashed suffix.
Useful? React with 👍 / 👎.
…e table length - Rate-limit windows lived on the per-scope effect in-mem table, which a reorg wipes (beginRollbackDiff clears state.effects), refilling the budget on replay. Keep them in a survivor dict on IndexerState (not cleared on rollback), keyed by cache table name; each recreated in-mem table reuses the same window. Rate limiting reflects real API throughput, not indexing progress. + regression test. - Reject effect cache table names longer than PostgreSQL's 63-char identifier limit in makeCacheTable, instead of letting PG silently truncate and diverge from what cache discovery reads back. - Make the per-chain rate-limit test assert that chain 2 bypasses chain 1's queue (order) rather than relying on which call resolves first. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
An effect name long enough to overflow the scoped identifier is unrealistic; the guard isn't worth the runtime throw. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
Effect runtime state was two loose dicts on IndexerState with divergent rollback lifecycles (cache wiped by beginRollbackDiff, rate-limit windows deliberately kept), an invariant that lived only in a comment. Introduce a nested IndexerState.EffectState module (mirroring EntityTables) that owns both maps and exposes getTable / forEach / resetForRollback. The rollback semantics — drop cache tables, preserve rate-limit windows — are now enforced by resetForRollback rather than remembered. Not folded into ChainState/CrossChainState: effect state is keyed by (effect, scope) and cross-chain effects have no chain, so it's a separate concern from chain fetch/coordination state. Behavior-preserving: InMemoryStore.getEffectInMemTable and Writing now delegate to the module; all effect/rollback tests pass unchanged. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
| // Owns all per-(effect, scope) runtime state and its lifecycle. The two maps | ||
| // have different rollback semantics, so keeping them together with an explicit | ||
| // `resetForRollback` makes the invariant enforced rather than remembered. | ||
| module EffectState = { |
There was a problem hiding this comment.
Let's have it as a separate file
| Object.defineProperty(this, "_chainId", { value: chainId }); | ||
| Object.defineProperty(this, "_effectName", { value: effectName }); |
There was a problem hiding this comment.
Let's move Object.defineProperty(effectContextPrototype, "chain", {
to constructor function.
1 - don't have getter for case return { id: this._chainId };
2 - only have getter for cross chain
3 - move getter function to the top level to avoid recreating it on every call
| queryEffectCache: string => promise<array<{"id": string, "output": JSON.t}>>, | ||
| queryEffectCache: 'input 'output. ( | ||
| Envio.effect<'input, 'output>, | ||
| ~scope: Internal.chainScope=?, |
There was a problem hiding this comment.
Let's have the field required
…chain field, required scope
- Move the EffectState module out of IndexerState into its own EffectState.res
/ .resi file.
- context.chain: install it in the EffectContext constructor instead of a
prototype getter — a plain data field `{ id }` for chain-scoped effects (no
getter), and only cross-chain contexts install a shared top-level throwing
getter (created once, not per context).
- MockIndexer.queryEffectCache: make the `~scope` argument required; pass it
explicitly at all call sites.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/envio/src/EffectState.res (1)
32-32: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the redundant field comment.
rateLimitState’s type already conveys this behavior. As per coding guidelines,**/*.res: “Default to writing no comments” and “Don't write a comment that restates what the code already says.”🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/envio/src/EffectState.res` at line 32, Remove the redundant comment immediately above rateLimitState in EffectState, leaving the field and its existing type unchanged.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@packages/envio/src/EffectState.res`:
- Line 32: Remove the redundant comment immediately above rateLimitState in
EffectState, leaving the field and its existing type unchanged.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 54ef3897-f9a6-491f-aa72-925f5231a110
📒 Files selected for processing (11)
packages/envio/src/EffectState.respackages/envio/src/EffectState.resipackages/envio/src/InMemoryStore.respackages/envio/src/IndexerState.respackages/envio/src/IndexerState.resipackages/envio/src/LoadLayer.respackages/envio/src/UserContext.respackages/envio/src/Writing.resscenarios/test_codegen/src/handlers/EventHandlers.tsscenarios/test_codegen/test/E2E_test.resscenarios/test_codegen/test/helpers/MockIndexer.res
💤 Files with no reviewable changes (2)
- packages/envio/src/IndexerState.resi
- packages/envio/src/IndexerState.res
🚧 Files skipped from review as they are similar to previous changes (7)
- packages/envio/src/Writing.res
- scenarios/test_codegen/src/handlers/EventHandlers.ts
- scenarios/test_codegen/test/helpers/MockIndexer.res
- packages/envio/src/InMemoryStore.res
- packages/envio/src/LoadLayer.res
- packages/envio/src/UserContext.res
- scenarios/test_codegen/test/E2E_test.res
The option type already conveys "None when the effect has no rate limit". Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e46b65aa28
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let elapsed = Performance.secondsBetween(~from=inMemTable.prevCallStartTimerRef, ~to=timerRef) | ||
| if elapsed > 0. { | ||
| Prometheus.EffectCalls.timeCounter->Prometheus.SafeCounter.handleFloat( | ||
| ~labels=effectName, |
There was a problem hiding this comment.
Scope effect-call wall-time accounting
When a chain-scoped effect runs on multiple chains at the same time, this now uses each table's prevCallStartTimerRef but still writes to the single envio_effect_call_seconds{effect=...} series. For two overlapping 10s calls on chains 1 and 2, each scope contributes ~10s to the same counter, so the wall-time metric reports ~20s; before this state moved off the effect object it only counted the union of overlapping calls. Please either keep aggregate timing state per effect or add the scope label to this counter too.
Useful? React with 👍 / 👎.
| function throwCrossChainChainAccess() { | ||
| throw new Error('context.chain is not available on the cross-chain effect "' + this._effectName + '". Set \`crossChain: false\` in its options to scope the effect to a single chain, then read context.chain.id.'); | ||
| } | ||
| var crossChainChainDescriptor = { get: throwCrossChainChainAccess, enumerable: true }; |
There was a problem hiding this comment.
Keep the throwing chain getter non-enumerable
For default cross-chain effects, making this throwing getter enumerable means existing code that clones or serializes the context, such as {...context}, Object.assign({}, context), or JSON.stringify(context), now trips context.chain and fails even though it did not explicitly use the new chain API. Please omit the property from enumeration, or make only chain-scoped contexts expose enumerable chain, so ordinary context spreading/logging remains backward-compatible.
Useful? React with 👍 / 👎.
| if !(effectNameRe->RegExp.test(options.name)) { | ||
| JsError.throwWithMessage( | ||
| `Invalid effect name "${options.name}". Effect names may only contain letters, numbers, underscores and hyphens, because the name is used as the cache table name and cache file path.`, |
There was a problem hiding this comment.
Preserve safe legacy effect names
This rejects existing projects whose effect names contain safe characters like dots (for example token.metadata) even though the public API still types name as a plain string and the default crossChain: true path is otherwise meant to preserve existing cache identity. Dot-containing names are reversible with the .tsv suffix and work in quoted PostgreSQL identifiers, so please encode table/path segments or reject only truly unsafe separators instead of requiring every existing effect name to match this identifier subset.
Useful? React with 👍 / 👎.
prevCallStartTimerRef and active-call state moved per (effect, scope),
but the call_seconds/call_seconds_total/call_total counters were still
keyed by effect only. Overlapping calls on different chains double-counted
wall time into one series. Give these counters the same {effect, scope}
labels as the active-calls gauge so each scope tracks its own throughput.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
The name-validation regex rejected existing safe names like "token.metadata". Dots round-trip fine through the (name, scope) <-> table <-> path mapping (table names are quoted; the cache scanner strips only the ".tsv" suffix). Allow dots mid-name while still excluding path separators and forbidding a leading dot, so a name can never be "." / ".." or traverse out of the cache dir. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* fix: parse SVM accountFilters as array of AND-groups in public config (#1408)
The CLI emits accountFilters as Vec<Vec<SvmAccountFilterJson>> (AND-groups
OR-ed together, normalized from both the flat and any_of YAML shapes), and
the consumer in Config.fromPublic already maps it as nested groups. The
parse schema declared a flat array, so any SVM config using account_filters
failed to load with:
Invalid indexer config: Failed parsing at ["svm"]["programs"][...]
["accountFilters"]["0"]["position"]. Reason: Expected int32,
received undefined
Wrap the schema in one more S.array so it matches what the CLI emits and
what the consumer expects, and add a regression test.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* Move EVM event routing, decoding, and query construction to Rust (#1404)
* Move EVM event routing and decoding to the Rust clients
Give each onEventRegistration a chain-scoped sequential id (its index in
the chain's onEventRegistrations array) and pass the registrations -
id, isWildcard, sighash/topicCount, param metadata - into the Rust
EvmHypersyncClient and EvmRpcClient constructors. Rust now routes every
log to its registration (owning contract via the partition's
address -> contract-name index, wildcard fallback) before decoding:
- DecoderCore keys a per-MetaKey router (by_contract_name + wildcard)
and decodes with only the routed variant's param names, so items carry
flat params instead of a per-contract dict.
- get_event_items and getNextPage take the partition's
contractNameByAddress; items return onEventRegistrationId and logs
that route nowhere are dropped on the Rust side.
- The RPC client normalizes log addresses (lowercase/checksum) so they
match the routing index and the JS address type directly.
- ReScript sources resolve items with
onEventRegistrations[item.onEventRegistrationId]; EventRouter's EVM
half (getEvmEventId, fromEvmEventModsOrThrow) is deleted and
EvmChain.makeSources enforces the id = array index invariant.
- Registration-time duplicate/wildcard-collision validation is mirrored
as a backstop in the Rust decoder constructor.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0145w9f63kqQmFf7mWMDWmQc
* Make onEventRegistration.id immutable
id is derived purely from push order — assign it via record spread when
the registration lands in the chain's array (HandlerRegister.finishRegistration,
EvmChain.makeSources) instead of mutating an existing field.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0145w9f63kqQmFf7mWMDWmQc
* Move EVM query construction to the Rust clients
Pass the full per-(event, chain) registration to the Rust clients at
construction — EventParamsInput becomes EventRegistrationInput, gaining
dependsOnAddresses, the resolvedWhere topic selections (per-topic
Option<Vec<String>>, None = contract-addresses marker), and the
selected block/transaction field lists. A shared SelectionBuilder
(evm_hypersync_source/selection.rs) owns everything a query derives
from the partition's selection and current addresses:
- log selections: address-free pooling + topic0 compression,
per-contract address scoping, wildcard-by-address marker expansion
into lowercase padded address topics, in registration order so query
bytes stay stable for caching;
- HyperSync field selection: union over the selection's registrations
with the transactionIndex exclusion, plus the forced required fields;
- the address -> contract-name routing index, derived from the
partition's addressesByContractName instead of being passed
separately.
The napi query surface shrinks to the block range plus the partition's
registration ids and addressesByContractName: get_event_items takes an
EventItemsQuery and builds the HyperSync query internally; get_next_page
drops log_selections/contract_name_by_address for registration_ids/
addresses_by_contract_name. Both clients expose build_log_selections
for tests and debugging.
On the ReScript side the per-source getSelectionConfig machinery
(bucketing, materialization, WeakMap memoization) is deleted from
HyperSyncSource and RpcSource; sources just forward selection ids and
addresses. LogSelection keeps only parseWhereOrThrow and the
materialize helpers used by tests; Rpc.GetLogs drops the topic-query
types. JS selection-shape tests are rewritten against
buildLogSelections, and field-selection behavior is covered by Rust
unit tests. Mock registrations now need hex-decodable sighashes since
the client validates them at construction.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0145w9f63kqQmFf7mWMDWmQc
* Store onEventRegistrationIndex on items; resolve registrations via ChainState
Internal.item's Event variant now carries onEventRegistrationIndex (the
registration's chain-scoped array position, renamed from id) instead of
the registration object, so Rust-built items can be final and complete.
The full registration is resolved through the chain's registration
array: stored on ChainState.t and mirrored in a per-chain registry in
Internal (setOnEventRegistrations at chain-state startup,
addOnEventRegistration for simulate/test setups that synthesize items,
getItemOnEventRegistration for consumers without a chain state at hand
— ecosystem toRawEvent/toEventLogger, FetchState's clientAddressFilter,
ChainFetching, EventProcessing, batch materialization).
Simulate appends its synthetic registrations into the run's
registrationsByChainId chain arrays (the same arrays chain-state startup
installs) instead of a side registry, so item indexes stay valid after
startup replaces the per-chain entry.
Rename the napi surface to match: EventRegistrationInput.index,
registration_indexes on both query params, on_event_registration_index
on items.
Drop the parallel eventRegistrations option on HyperSyncSource/RpcSource
— the Rust registration inputs are now derived inside the sources from
onEventRegistrations via HyperSyncClient.Registration.
fromOnEventRegistrations (moved from EvmChain), removing a second field
that had to stay in lockstep with the lookup array.
Fix indexed dynamic-type event filters: tuple/array where values were
passed through raw (previously latent — they only crossed napi at query
time and never in tests; passing registrations at client construction
surfaced it as a startup failure). Encode them as keccak256 of the ABI
encoding like the chain does, trying a directly-passed tuple as one
value before falling back to an OR-list of tuples.
Remove dead code (Rust add_field/ensure_required_log_fields/
TopicSelection::has_filters, ReScript QueryTypes topic helpers) and
refactor-narration comments.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0145w9f63kqQmFf7mWMDWmQc
* Rename EventRegistrationInput to OnEventRegistration; clarify decoder field names
Match the ReScript-side naming for the registration crossing the napi
boundary, and make the decoder's routing fields say what they hold:
EventVariant.on_event_registration_index, RegisteredEvent.
wildcard_variant_idx / variant_idx_by_contract_name.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0145w9f63kqQmFf7mWMDWmQc
* Fix event registration ownership and indexed topic encoding (#1412)
* Fix event registration ownership and topic encoding
* Allow empty standalone mock source responses
* Store registration state on mock sources
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Replace test-only log selection API with E2E coverage (#1413)
* Add RPC source contract pin framework (#1416)
* Centralize config parsing tests around YAML (#1421)
* Centralize config parsing tests around YAML
* Explain SVM pubkey validation dependency
* Include licenses directory in published envio package (#1422)
* Fix incorrect license in envio package.json
The published envio package declared GPL-3.0, but the project ships a
proprietary SaaS EULA (licenses/LICENSE.md), not a GPL license. Mark the
package UNLICENSED to reflect its proprietary terms.
* Ship the EULA and reference it from the license field
The envio package is proprietary (licenses/LICENSE.md is a SaaS EULA), so
use the standard 'SEE LICENSE IN LICENSE.md' form instead of UNLICENSED, and
copy the EULA to the published package root so the reference resolves for
consumers. Add LICENSE.md to the artifact verifier's required files.
* Ship the full licenses directory with the envio package
The licenses/ dir holds four files: the HyperIndex software EULA (EULA.md),
the SaaS EULA (LICENSE.md), the CLA, and an overview README. The npm package
is the HyperIndex software, so point the license field at licenses/EULA.md and
copy the whole directory into the published package. Add 'licenses' to the
files allowlist (npm only force-includes a root LICENSE, not a subdirectory)
and verify every license file ships.
* Point license field at the licenses overview README
licenses/README.md is the licensing index: it explains which terms apply to
the software, generated code, and hosted service, and links the specific
EULAs. Reference it from the license field so consumers land on the overview
rather than a single EULA that only covers part of the picture.
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Enable strict warning checks in ReScript configurations (#1424)
* Treat ReScript warning 23 as an error in indexer configs
Promote the "useless record with clause" warning to an error in the
generated-project template and the test scenarios. The envio runtime
package already errors on all warnings via "+a".
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DGX7HGV5nCwFHHoazo8dCM
* Enforce all ReScript warnings as errors in test scenarios
Set warnings.error to "+a" for the test_codegen, fuel_test, and svm_test
scenarios, matching the envio runtime package. Leave the user-facing
generated-project template without a warnings override.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DGX7HGV5nCwFHHoazo8dCM
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Improve rollback logging and conditional event registration logging (#1425)
* Improve indexer logs for contract-register events and rollback range
Omit numContractRegisterEvents from the "Finished querying" log when it's
zero, and log the per-chain rollback block range for all affected chains
at info level so reorg rollbacks aren't limited to the reorg chain's
target block.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xvxwf6mi6rT2AV16sx2KSL
* Emit per-chain rollback logs and quiet the batch-wait log
Drop the "Waiting for batch..." log to trace, remove the aggregate
"Rolled back chains on reorg" log, and replace the trace-level "Finished
rollback on reorg" log with a per-chain info "Rollbacked" log carrying the
chain id, from/to block range, rolled-back event count, and reorg-chain
flag.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xvxwf6mi6rT2AV16sx2KSL
* Split rollback entity changes into a separate trace log
Restore the entity deleted/upserted detail as its own trace-level log and
drop the isReorgChain field from the per-chain "Rollbacked" info log.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xvxwf6mi6rT2AV16sx2KSL
* Avoid chainId binding collision on rollback logs
Build the rollback logger without inheriting the reorg chain's logger,
which bound its chainId onto every line and collided with the per-chain
chainId on the "Rollbacked" logs. The reorg chain is identified by the
reorgChain param instead.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xvxwf6mi6rT2AV16sx2KSL
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Extract client-side address filtering from FetchState (#1414) (#1427)
* Filter over-fetched events before contract registration
Over-fetched events (a merged partition returning an address before its
effectiveStartBlock, or a wildcard param referencing an address registered
after the log's block) were running their contractRegister handlers and
spawning dynamic contracts before being dropped from the buffer.
Apply the client-side address filter to the contract-register set before
running the handlers. Extract the predicate as FetchState.filterByClientAddress
and expose it through ChainState so ChainFetching can gate registration; the
buffer is still filtered after registration in handleQueryResult, so events
referencing a contract registered in the same batch keep routing to handlers.
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
* Move client address filter fully before contract registration
Follow-up to the previous commit: instead of only gating the contract-register
set, apply the client-side address filter to the whole response up front, so an
over-fetched event neither spawns dynamic contracts nor enters the buffer.
This is only correct if a non-wildcard event for an address registered in the
same batch can't appear before its registration — which a real backend
guarantees, since a query only returns logs for the addresses it was sent. The
simulate source didn't model that (it dumped every item on the first call), so
make it faithful: return only items matching the query's block range, selection,
and (for non-wildcard events) address set, delivering each once; wildcards are
over-fetched for the client filter to gate, mirroring HyperSync. A contract
registered mid-run now surfaces its events in the follow-up query the
registration triggers, exactly as in production.
Parse simulate items at the process's startBlock (not the config default) so
they land in the range the source is queried over. The dead-input tracker stays
downstream, observing processed batches, so it still reports items excluded by
any filter.
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
* Merge buffer with a single sort-free pass instead of re-sorting
Buffer accumulation re-sorted the whole buffer on every response via
Array.sort(compareBufferItem) — an O(n log n) pass whose comparator crosses the
JS↔native boundary on each comparison — plus a Set of string keys for dedup.
Replace it with mergeIntoBuffer: the buffer is already sorted, so insertion-sort
just the (small, usually ascending) response and merge the two runs in one linear
pass, dropping duplicates as adjacent-equal. Comparison is inlined
(compareBufferItem now returns an int with explicit field compares and a
registration-index tiebreaker) with no Array.sort callback and no allocated key.
updateInternal assumes a sorted buffer (hot paths pass mutItemsSorted=true) and
normalizes arbitrary input otherwise; onBlock items are generated as their own
sorted run and merged in the same way.
~14-20x faster on realistic buffers (see packages/envio/bench). Adds a
mergeIntoBuffer correctness test.
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
* Address review: drop bench, single onBlock merge, simplify test helper
- Delete the standalone benchmark script.
- updateInternal now folds onBlock items into the buffer with a single merge at
the end instead of merging mid-function; block items stay their own sorted run
so the merge remains linear.
- makeInitialWithOnBlock returns the fetch state directly (indexing addresses
were unused by every caller).
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
---------
Co-authored-by: Claude <noreply@anthropic.com>
* SVM: exclude failed-transaction instructions (#1428)
HyperSync serves instructions from failed Solana transactions and the
runtime delivered all of them to onInstruction handlers, silently
over-counting (~18% for SPL TransferChecked over the sampled slots).
Exclude instructions whose parent transaction did not commit, matching
EVM (reverted-tx logs never exist) and the old RPC `!tx.meta.err` pattern.
Filter client-side in SvmHyperSyncSource.getItemsOrThrow on the
`isCommitted` flag HyperSync already delivers on every instruction row (a
required column, zero extra bandwidth). The current query API cannot push
this down (InstructionSelection exposes only `is_inner`; instruction and
transaction selections union at block level rather than joining), so the
client-side check stands until HyperSync adds a server-side `is_committed`
predicate, at which point it becomes a redundant safety net.
No opt-in knob for now: keep the surface minimal and add a config option
(e.g. per-instruction `include_failed`) if and when someone needs failed
transactions. Deferring it also leaves the opt-in design open rather than
committing to a config shape prematurely.
HOS-1610
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Dmitry Zakharov <dzakh.dev@gmail.com>
* Fix rollback handling for deleted entities (#1431)
* Fix rollback handling for deleted entities
* Return rollback removed IDs directly
* Harden rollback test error handling
* Add Tron chain to fix hypersync health check (#1436)
Tron (chain_id 728126428) is served publicly by the HyperSync API but was
missing from the Network enum, causing the health check to fail.
Claude-Session: https://claude.ai/code/session_011GxCWhUKxvdy8zgg44wvMr
Co-authored-by: Claude <noreply@anthropic.com>
* Add per-chain effect caching and rate limiting (#1432)
* feat(effects): per-chain cache scoping via crossChain option
Add a `crossChain` option to the Effect API (defaults to `true`). When
`crossChain: false`, an effect's cache and rate-limit window are isolated
per chain and the handler can read `context.chain.id`.
- Public API: `crossChain?: boolean` on effect options; required
`context.chain.id` in ReScript and TypeScript types. Reading
`context.chain` on a cross-chain effect throws a guiding error.
- Scope model (`CrossChain | Chain(int)`) resolved from the effect config
and the current handler chain. Nested calls follow: handler -> either;
chain -> either; cross-chain -> cross-chain; cross-chain -> chain fails
before cache lookup with both effect names and remediation.
- Per-scope runtime boundary: in-memory cache, in-flight dedup, rate-limit
window/queue and active-call state are keyed by the resolved cache
address; the canonical input key is unchanged.
- Central reversible mapping `Internal.EffectCache` between
(effectName, scope) <-> table name <-> cache file path, used everywhere
instead of prefix slicing. Cache metadata is keyed by the full address.
- Postgres: cross-chain tables `envio_effect_<name>`, chain-scoped
`envio_<chainId>_effect_<name>`; discovery matches both formats.
`.envio/cache` gains numeric per-chain subdirectories; restore rejects
malformed chain directories and supports one directory level; dump does
the exact reverse mapping.
Tests: address round trips / legacy / coexistence / invalid parsing,
per-chain dedup and independent rate limits, cross-chain sharing, and an
E2E covering context.chain.id, the guiding errors, and per-chain
persistence.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* refactor(effects): unboxed effectScope, enumerable chain getter, exact error tests
Address review feedback:
- Make `context.chain` an enumerable own getter closing over the resolved
chain, dropping the hidden `_chainId`/`_effectName` instance fields.
- Mark `effectScope` `@unboxed` (CrossChain -> "crossChain", Chain(id) ->
the raw id, discriminated by runtime type).
- Assert the exact cross-chain `context.chain` and nested cross-chain ->
chain-scoped error messages in the E2E test.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* refactor(effects): address review — generic chainScope, resolved-table write path, prototype getter
- Rename `effectScope` -> `chainScope` (generic; reused for entities later).
- Persistence write path no longer threads effect+scope: `updatedEffectCache`
and `setEffectCacheOrThrow` take the resolved `table` (the cache address) +
item schema. The in-mem table now holds its built `table`, so the address is
resolved once in `getEffectInMemTable` and reused by load/snapshot/write.
- Move the `context.chain` getter back onto the prototype (enumerable, like
`log`), reading per-instance non-enumerable fields.
- Collapse the two MockIndexer cache-query helpers into one
`queryEffectCache(effect, ~scope=?)`.
- Tighten the crossChain docs: concise and user-facing, no table/file internals.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* Add scope label to per-scope effect gauges and strict chain-id parsing (#1435)
The envio_effect_active_calls, envio_effect_cache, and envio_effect_queue
gauges are backed by per-scope state since caching became chain-scoped, so
scopes of the same effect clobbered each other's value. Label them with
scope: "crossChain" | <chain id>.
Cache directory chain ids are now parsed strictly: "1foo" and "007" are
rejected instead of being treated as chains 1 and 7 via parseInt semantics.
Claude-Session: https://claude.ai/code/session_011YLPufR6wf9LYFAsNjKz1t
Co-authored-by: Claude <noreply@anthropic.com>
* fix(effects): validate effect names and guard cache-table discovery by columns
Two review points not covered by #1435:
- Validate effect names to `[A-Za-z0-9_-]+` in createEffect. The name is used
as a cache table name and a .envio/cache path segment, so path separators and
traversal (`a/b`, `../evil`) must be rejected to keep the
(name, scope) <-> table <-> path mapping reversible.
- Cache-table discovery now also requires the effect-cache column shape
(exactly `id` + `output`), so a user entity table that matches the reserved
name pattern is never mistaken for an effect cache.
#1435 already addressed the per-scope metric-gauge clobbering (via a scope
label) and strict chain-id parsing, so those are not duplicated here.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* fix(effects): preserve rate-limit budget across rollbacks; guard cache table length
- Rate-limit windows lived on the per-scope effect in-mem table, which a reorg
wipes (beginRollbackDiff clears state.effects), refilling the budget on
replay. Keep them in a survivor dict on IndexerState (not cleared on
rollback), keyed by cache table name; each recreated in-mem table reuses the
same window. Rate limiting reflects real API throughput, not indexing
progress. + regression test.
- Reject effect cache table names longer than PostgreSQL's 63-char identifier
limit in makeCacheTable, instead of letting PG silently truncate and diverge
from what cache discovery reads back.
- Make the per-chain rate-limit test assert that chain 2 bypasses chain 1's
queue (order) rather than relying on which call resolves first.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* revert(effects): drop the 63-char cache table name guard
An effect name long enough to overflow the scoped identifier is unrealistic;
the guard isn't worth the runtime throw.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* refactor(effects): encapsulate effect state in an EffectState module
Effect runtime state was two loose dicts on IndexerState with divergent
rollback lifecycles (cache wiped by beginRollbackDiff, rate-limit windows
deliberately kept), an invariant that lived only in a comment.
Introduce a nested IndexerState.EffectState module (mirroring EntityTables)
that owns both maps and exposes getTable / forEach / resetForRollback. The
rollback semantics — drop cache tables, preserve rate-limit windows — are now
enforced by resetForRollback rather than remembered. Not folded into
ChainState/CrossChainState: effect state is keyed by (effect, scope) and
cross-chain effects have no chain, so it's a separate concern from chain
fetch/coordination state.
Behavior-preserving: InMemoryStore.getEffectInMemTable and Writing now delegate
to the module; all effect/rollback tests pass unchanged.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* refactor(effects): address review — extract EffectState, constructor chain field, required scope
- Move the EffectState module out of IndexerState into its own EffectState.res
/ .resi file.
- context.chain: install it in the EffectContext constructor instead of a
prototype getter — a plain data field `{ id }` for chain-scoped effects (no
getter), and only cross-chain contexts install a shared top-level throwing
getter (created once, not per context).
- MockIndexer.queryEffectCache: make the `~scope` argument required; pass it
explicitly at all call sites.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* docs(effects): drop redundant rateLimitState comment
The option type already conveys "None when the effect has no rate limit".
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* fix(effects): scope effect-call timing metrics per chain
prevCallStartTimerRef and active-call state moved per (effect, scope),
but the call_seconds/call_seconds_total/call_total counters were still
keyed by effect only. Overlapping calls on different chains double-counted
wall time into one series. Give these counters the same {effect, scope}
labels as the active-calls gauge so each scope tracks its own throughput.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* fix(effects): allow dots in effect names
The name-validation regex rejected existing safe names like "token.metadata".
Dots round-trip fine through the (name, scope) <-> table <-> path mapping
(table names are quoted; the cache scanner strips only the ".tsv" suffix).
Allow dots mid-name while still excluding path separators and forbidding a
leading dot, so a name can never be "." / ".." or traverse out of the cache dir.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Replace prune throttler with smart scheduling in write loop (#1444)
* Fix history prune racing batch writes and losing rollback anchors
The stale-history prune ran on its own throttler concurrently with batch
writes. Its anchor deletion relies on "no history after the safe
checkpoint", which a concurrently committing batch falsifies: the batch's
backfill sees the anchor and skips, the prune sees no post-safe rows and
deletes the anchor, and after both commit the entity has history only
above the safe checkpoint. A later rollback then deletes the entity
instead of restoring it.
Move pruning into the write loop so it can never overlap a history write
for the same entity:
- Each write picks up to 5 pg entities not pruned for the prune interval,
excluding entities written in the batch (rollback writes touch every
history table, so they get none), and prunes them one at a time
concurrently with the batch write, awaited before the next write.
- Entities starved of the concurrent prune (eg written in every batch)
are force-pruned sequentially right after the write, once they haven't
been pruned for 5x the interval.
- Prune failures are logged instead of failing the write loop.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UjkHvbFKZxk1L3JY6e7HCt
* Select prune targets in a single pass over entities
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UjkHvbFKZxk1L3JY6e7HCt
* Throttle failed prune retries and keep checkpoint pruning out of rollback writes
Record the prune attempt time on failure too, so a failing entity retries
on the prune interval instead of on every write. Run checkpoint pruning
only alongside a concurrent entity prune; when nothing runs concurrently
(eg a rollback write) it moves to the forced phase after the write.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UjkHvbFKZxk1L3JY6e7HCt
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Refactor query sizing to water-fill budget across chains (#1392)
* Make multichain fetch scheduling chain-controlled
Replace the per-partition/per-query greedy admission scheduler with a
per-chain waterfall: CrossChainState.checkAndFetch visits chains
furthest-behind first, handing each its remaining share of the shared
buffer budget. ChainState turns that budget into a soft target block
using a new chain-wide event density (seeded from cumulative progress,
smoothed with an EMA per batch), and FetchState.getNextQuery sizes
known-density partitions against that target block while splitting
whatever budget is left across partitions with unknown density.
This concentrates fetch effort on the bottleneck chain per tick instead
of scattering a shared item budget across every chain's full candidate
query set.
* Fix probe-split eligibility and query ordering in FetchState.getNextQuery
The unknown-density probe split counted partitions with nothing left to
query (already at their endBlock/mergeBlock/knownHeight ceiling), inflating
the divisor and under-sizing eligible partitions' queries. Add a
hasEligibleRange check mirroring pushQueriesForRange's own gate to exclude
them.
Splitting partitions into known/unknown passes also broke the original
idsInAscOrder query ordering that several tests assert on positionally;
restore it by sorting the final query list back into partition order.
Update FetchState_test.res fixtures accordingly, including a case that
needed distinct expected values across three eligibility scenarios that
previously shared one fixture.
* Redesign FetchState.getNextQuery as an even per-partition water-fill
Query creation now splits the chain's range budget evenly across
in-range partitions each round, rather than sizing every known-density
partition against the full chain target while unknown-density
partitions fought over the leftover. A partition already holding more
budget than its even share (e.g. from an earlier tick's in-flight
query) sits out a round so its share flows to the others, and the
split is recomputed each round against the shrinking set of partitions
still needing more.
Also:
- Rename estResponseSize -> itemsTarget throughout, since the field is
now both the server-side maxNumLogs-style cap and the budget
reservation/consumption unit, not just an estimate.
- Bucket queries by partition index as they're created instead of
sorting the whole result at the end of every tick.
- Only trust a partition's density once it has two responses
(matching the existing chunking-heuristic gate); a single response
is too noisy to size the next query from.
- Smooth the chain-wide density EMA as (old + new) / 2 instead of
(2*old + new) / 3.
* Address review feedback on the water-fill scheduler: dedupe reserved-sum
walk, tighten round bound, add coverage
- getNextQuery walked every partition's mutPendingQueries twice (once
for chainReserved, again to seed reservedByPartition per partition).
Merge into a single pass.
- Replace the unproven roundsRef < 1000 safety cap with a provable
bound: every active partition either finishes or advances its chunk
count each round, capped at maxPendingChunksPerPartition, and all
active partitions progress in lockstep (not one at a time), so no
partition can outlive maxPendingChunksPerPartition + 1 rounds.
- Add ChainState_test.res covering the chain density seed (from
resumed progress) and the EMA blend.
- Add a CrossChainState_test.res case pinning the waterfall's actual
cross-chain budget flow: a chain whose real range caps its
consumption below its share leaves the remainder for the next chain.
* Make the water-fill round's per-partition share order-independent
Each round computed ipb = rangeBudget/n once, but then capped every
partition's actual budget at min(rangeBudget, ipb - reserved) and
decremented rangeBudget after each partition — so a partition
processed earlier in the same round (e.g. one forced to overshoot its
share via the "at least one full chunk" rule) shrank the pool for
whoever came after it. Same reservations, different iteration order,
different split (and total consumption could even exceed rangeBudget
depending on order).
Fix: every partition's share for a round is ipb - reserved, fixed for
the whole round; rangeBudget is only re-derived once, from the round's
actual total consumption, after every partition has had its fixed
shot. A partition can still overshoot its own share, but it can no
longer steal from another partition in the same round.
Also fixes a SourceManager_test.res assertion that was pinned to the
old order-dependent rounding artifact (three identical partitions
splitting a budget three ways used to get 16667/16667/16666; they now
all get 16667, as they should since they're indistinguishable).
* Redistribute a filled partition's leftover budget in the water-fill (#1394)
The per-partition round budget was `ipb - reserved`, where `ipb` was an
even share of only the *remaining fresh* budget (`rangeBudget / n`) while
`reserved` accumulated each partition's full footprint (existing in-flight
+ gap-fill + this call's prior-round emissions). Those two are on different
scales, so once a chunked partition's running reservation passed a later
round's fresh share, `ipb - reserved` went negative and the partition was
dropped — leaving budget unspent even though it still had range to fetch
and a sibling had just freed its share by filling early.
Compute the round's level as a real water-fill line — (remaining fresh
budget + the still-not-filled partitions' current footprint) / count —
and top each partition up toward it. A partition already above the line
gets nothing (its head start is its whole share); the rest absorb the
leftover, so the budget is fully used and per-partition totals stay even.
The loop now runs until either the not-filled set drains or the whole
fresh budget is reserved, dropping the redundant round cap: a partition
survives a round only by advancing chunksUsedThisCall (bounded by
maxPendingChunksPerPartition) or consuming budget, so it terminates on
its own.
Add a regression test: a range-capped partition and a deep partition
splitting a 900-item budget — the deep one now absorbs the capped one's
freed share (4 chunks / 720 items) instead of stopping at 2.
Claude-Session: https://claude.ai/code/session_0134TTgxQ3ci5mWUnt928yr9
Co-authored-by: Claude <noreply@anthropic.com>
* Cap unknown-density probe query at maxItemsTarget
An unknown-density partition's open-ended probe was sized to its full even
share of the chain's budget with no ceiling. When such a chain leads the
furthest-behind waterfall, that share is the entire cross-chain buffer pool,
so its single probe consumed 100% of the remaining budget and starved any
sibling chain needing its own first probe in the same tick (e.g. multiple
chains entering the reorg threshold together).
Cap the probe at maxItemsTarget (10_000), restoring the old bounded-default
ceiling. The leftover budget flows to the next chain via checkAndFetch's
remaining subtraction, exactly as before.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GBSAcMXTNy2K8i16bkJELo
* Don't seed chain density from a zero-event batch
The resume-seed path only sets chainDensity once numEventsProcessed > 0, but
the per-batch EMA update seeded Some(0.) after any progress-only batch (blocks
advanced, no events), contradicting that documented behavior and making the
first real batch blend against 0 instead of seeding from its own density.
Guard the EMA seed on the batch having events, matching the resume path. The
Some(oldDensity) blend is unchanged.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GBSAcMXTNy2K8i16bkJELo
* Adjust itemsTarget setting logic
* Enforce reservation == server cap and stop chunking without trusted density
- Floor itemsTarget at 1 at creation (densityItemsTarget, water-fill chunk
loop, probe) so a query's budget reservation always equals the
maxNumLogs-style cap sent to the server; drop SourceManager's 2000-item
fallback that let density-0 queries return up to 2000 unaccounted items.
- Emit density-priced chunks only for a trusted positive density; density-0
and unknown-density partitions get a single open-ended probe sized at the
even split of the tick's fresh budget (maxItemsTarget cap removed). This
removes the chunkCost=0 path that flooded 10 free hard-bounded chunks per
partition and froze the 1.8x range growth.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Extract getTrustedDensity helper for water-fill chunk sizing
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Make query itemsTarget an int and trim redundant comments
The ceil-to-int conversion now happens once at query creation, so the
reservation, the budget accounting, and the server cap all use the same
integer value; SourceManager passes it through untouched.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Price gap-fill by trusted density with available-density fallback
Gap queries now use getTrustedDensity: chunks only on a trusted positive
density (same rule as the water-fill); a trusted-zero density prices the
whole gap as one open query, and a partition with no density signal prices
it by available density — its equal-divide budget spread over the remaining
range this tick — so a small gap reserves proportionally little instead of
a noisy one-sample estimate or a NaN from dividing by a zero range.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Cap follower chains at the leader's target progress in the waterfall
Chains beyond the most-behind one in the budget waterfall are now capped
at that leader's target progress, mapped onto their own block range
(ChainState.progressAtBlock/blockAtProgress), so no chain runs further
ahead than the chain the shared buffer pool is prioritizing. A chain
visited after the pool is exhausted simply sits out the round — its
reservations release as responses land, so the next tick redistributes.
FetchState's dynamic-contract partition merge now inherits the sum of
its parents' trusted densities (weighted onto the merged partition's
min query range) instead of resetting to 0, so a merge with density
history doesn't regress to an unpriced probe.
Update E2E/rollback tests to the now-serialized cross-chain query
dispatch (most-behind chain queries first; siblings follow once its
response releases budget) and to give density-dependent chunking tests
a nonzero item count to trust.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Cap a clamped chain's fresh budget at its density-priced range cost
When a chain's target block is clamped (head, endBlock, or the
cross-chain alignment cap), a known-density chain's fresh budget is now
capped at density x clamped range (in-flight reservations stay on top so
they don't crowd out new partitions). The unused remainder stays in the
waterfall's pool and flows to the next chain in the same tick, instead
of being held by an oversized probe until the response lands.
This also removes the drain loop the infinite-reorg-loop test needed:
the non-reorg chain's post-rollback refetch now reserves only its real
range cost, so the reorg chain gets budget immediately.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Give head-bound queries 2x density headroom in the budget cap
A query clamped at the head sized exactly at density x range truncates at
the server cap whenever the range is slightly denser than the estimate,
forcing an immediate catch-up query for the last few blocks. Double the
range cost for head-bound targets so one query usually suffices; the
extra reservation releases as soon as the response lands.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Refine chain budget caps: endBlock ceiling, 5k probe cap, 3x head headroom
- targetBlock now clamps at endBlock (when below the head) via a shared
fetchCeiling helper, so endBlock'd chains stop sizing and aligning
against range they'll never fetch.
- A chain with no positive density signal caps its fresh budget at 5k,
so one unknown chain measuring its first responses no longer holds the
whole cross-chain pool.
- Head/endBlock-bound queries get 3x (was 2x) density headroom against
truncating at the server cap and needing a catch-up query.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Fix clippy::useless_borrows_in_formatting across cli package
Remove redundant & references in format!/anyhow! arguments flagged by
the CI-pinned clippy (rust 1.97). Pre-existing on the base branch,
unrelated to the SourceManager/waterfall changes in this PR — fixed
here since it was blocking cargo-test from going green.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Fix clippy::to_string_in_format_args exposed by the previous fix
Removing the redundant & in anyhow!'s self.id.to_string() surfaced a
second lint on the same line: ChainId (u64) already implements Display,
so .to_string() inside the format arg is itself redundant.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Fix clippy useless_borrows_in_formatting errors blocking CI
main's cargo-test job started failing clippy (-D warnings) on pre-existing
code after a stable-toolchain drift (no rust-toolchain pin), unrelated to
this PR's scheduling changes but inherited via the origin/main merge.
Removed the redundant `&` in format!/anyhow! args across 6 files, and
dropped a now-also-flagged explicit .to_string() on a Display type in
validation.rs.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GBSAcMXTNy2K8i16bkJELo
* Pour water-fill budget at an exact level and tighten chain budget edges
- Replace the per-round mean line in FetchState.getNextQuery with an exact
water level (sum of top-ups equals the poured budget), so uneven in-flight
reservations can no longer inflate other partitions' allotments past the
fresh budget
- Size unknown-density probes by their water-fill allotment instead of a
fixed pre-round even split, so leftover budget reaches the partitions
without reservations instead of being stranded
- Gate the 3x head headroom on the chain having caught up once (isReady)
- Blend chain density weighted by the batch's block span instead of a flat
(old + new) / 2
- Clamp progressAtBlock at 0 for the initial -1 fetch frontier
- Skip chains with no known height in the cross-chain waterfall so they wait
for a block instead of setting a degenerate alignment line
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KvUhc8DhbxjGPEtHoDNThJ
* Shrink density blend window to 100 blocks
Small batches (a few blocks) should barely nudge the chain density estimate,
while anything spanning 100+ blocks is a trustworthy fresh sample.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KvUhc8DhbxjGPEtHoDNThJ
* Add chunk headroom multiplier for budget-aware query sizing (#1400)
* Add chunk itemsTarget headroom and budget-driven chunk emission
Chunk reservations now carry a headroom multiplier over the density
estimate (1.5x during backfill, 3x in realtime, chosen in
CrossChainState.checkAndFetch and threaded down to
FetchState.getNextQuery), so a denser-than-expected range doesn't
truncate at the server cap. Open-ended probes stay allotment-sized.
The emit loop replaces the precomputed chunkCost/affordable estimate
with per-chunk actual itemsTarget accounting: the first chunk always
emits full-size, subsequent chunks only while they fit the budget, and
the min-one-chunk force applies once per call instead of once per
water-fill round.
Cap-hit truncations (partial response with itemsCount >= itemsTarget)
no longer update the chunk range history — they reflect our own
reservation, not server capacity. Sub-cap partials still do.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KpFcYPn8UbQfaEfW6gjant
* Restore min-one-chunk per water-fill round
A leftover re-pour forces a full chunk again, so the budget never
strands on chunk quantization; the overshoot stays bounded at one
chunk per partition per round and self-corrects via the reported
reservations. Drops the per-call emittedThisCall bookkeeping.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KpFcYPn8UbQfaEfW6gjant
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Implement cold-chain targeting and density-aware query sizing (#1401)
* Contain queries to the chain target block and rework cold-start sizing
- No chunk or gap-fill query starts past chainTargetBlock; emitted chunks
keep their full span, with endBlock/mergeBlock staying the hard bounds.
Skipped gaps regenerate from the pending-walk and fill once the target
reaches them.
- A chain with no density signal targets frontier + coldTargetRange
(init 20k), doubling whenever it goes idle without producing a signal,
capped at the fetch ceiling. The cross-chain waterfall clamps a cold
chain to min(5k, targetBufferSize), replacing the internal probe clamp,
and a cold leader no longer sets the alignment line.
- Query sizing uses effectiveDensity = max(processing EMA, ready-buffer
density), so a dense buffer overrides a stale-low EMA and ready items
alone take a chain out of cold mode.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018CiEziFbVe1P3Y6iuyfT5Z
* Replace cold-window doubling with a fixed 20k range
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018CiEziFbVe1P3Y6iuyfT5Z
* Span ready-buffer density from the processing block number
The buffer is consumed at batch creation while committed progress only
catches up after the batch commits, so mid-batch the density's numerator
shrank without the denominator following. Track the in-flight batch's
progress as processingBlockNumber (advanced in advanceAfterBatch, caught
up in applyBatchProgress, rewound on rollback) and use it as the span's
lower boundary.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018CiEziFbVe1P3Y6iuyfT5Z
* Warm the chain with seed events in the partition-merge E2E test
A chain with no density signal now targets frontier + 20k, which gates the
far DC partitions this test fetches in parallel. Seed 100 events in the
registering response so the chain has a density signal and enough range
budget for DC2's full 10-chunk pipeline; cold gating itself is covered by
unit tests.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018CiEziFbVe1P3Y6iuyfT5Z
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Reserve budget at honest itemsEst and tune scheduler defaults (#1403)
* Reserve budget at honest itemsEst instead of headroomed itemsTarget
Queries now carry both itemsTarget (server-side cap, sized with the chunk
headroom multiplier) and itemsEst (raw density estimate). Reservations,
pendingBudget, and water-fill footprints use itemsEst, so headroom no longer
throttles pipeline depth. The extra 3x budget cap for caught-up chains is
dropped — truncation safety lives solely in the itemsTarget cap, keeping
realtime headroom at 3x instead of compounding to 9x. Aligned chains may now
run 5% past the leader's line to stop clamp flapping when progress tracks
closely.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QyDQ2imktXA4jL8PtWYSmd
* Raise default target buffer to 100k and chunk pipeline cap to 12
Measured on the erc20 template against real HyperSync data: at 50k the dense
chain's buffer drained to zero in a quarter of samples (processing starved on
fetching), while at 100k it almost never does and throughput matches the
processing ceiling. Beyond 100k there's no further gain — 300k only grows the
resident buffer. The chunk cap rarely binds at 12 but gives the pipeline
headroom at the larger budget.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QyDQ2imktXA4jL8PtWYSmd
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Fix future end block progress alignment (#1406)
* Keep below-head chains polling instead of dropping them (NothingToQuery)
At realtime (and during backfill), when one chain falls far behind and its
query reservation drains the shared fetch-buffer budget, a chain that is below
its own head gets no query this tick. Being below head it also won't wait for a
new block, so getNextQuery returns NothingToQuery. checkAndFetch never
dispatches NothingToQuery, so that chain stops fetching AND stops polling
getHeightOrThrow — its head tracking freezes. This reproduced two production
stalls: one right before the indexer enters isReady, and one after isReady
having queried only a few items.
Dispatch such a chain as WaitingForNewBlock so it keeps polling, mirroring the
existing knownHeight == 0 guard. A chain is still left idle (undispatched) when
it is genuinely so: caught up to its head/endblock, still draining in-flight
queries, or holding ready items that batch processing will drain and
re-schedule from.
Add an E2E regression test that drives two chains to realtime, then a divergent
height jump (leader far ahead, follower just past its own head), and asserts the
near-head follower keeps polling getHeightOrThrow while the leader backfills.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GBSAcMXTNy2K8i16bkJELo
* Extract client-side address filtering from FetchState (#1414)
* Filter over-fetched events before contract registration
Over-fetched events (a merged partition returning an address before its
effectiveStartBlock, or a wildcard param referencing an address registered
after the log's block) were running their contractRegister handlers and
spawning dynamic contracts before being dropped from the buffer.
Apply the client-side address filter to the contract-register set before
running the handlers. Extract the predicate as FetchState.filterByClientAddress
and expose it through ChainState so ChainFetching can gate registration; the
buffer is still filtered after registration in handleQueryResult, so events
referencing a contract registered in the same batch keep routing to handlers.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
* Move client address filter fully before contract registration
Follow-up to the previous commit: instead of only gating the contract-register
set, apply the client-side address filter to the whole response up front, so an
over-fetched event neither spawns dynamic contracts nor enters the buffer.
This is only correct if a non-wildcard event for an address registered in the
same batch can't appear before its registration — which a real backend
guarantees, since a query only returns logs for the addresses it was sent. The
simulate source didn't model that (it dumped every item on the first call), so
make it faithful: return only items matching the query's block range, selection,
and (for non-wildcard events) address set, delivering each once; wildcards are
over-fetched for the client filter to gate, mirroring HyperSync. A contract
registered mid-run now surfaces its events in the follow-up query the
registration triggers, exactly as in production.
Parse simulate items at the process's startBlock (not the config default) so
they land in the range the source is queried over. The dead-input tracker stays
downstream, observing processed batches, so it still reports items excluded by
any filter.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
* Merge buffer with a single sort-free pass instead of re-sorting
Buffer accumulation re-sorted the whole buffer on every response via
Array.sort(compareBufferItem) — an O(n log n) pass whose comparator crosses the
JS↔native boundary on each comparison — plus a Set of string keys for dedup.
Replace it with mergeIntoBuffer: the buffer is already sorted, so insertion-sort
just the (small, usually ascending) response and merge the two runs in one linear
pass, dropping duplicates as adjacent-equal. Comparison is inlined
(compareBufferItem now returns an int with explicit field compares and a
registration-index tiebreaker) with no Array.sort callback and no allocated key.
updateInternal assumes a sorted buffer (hot paths pass mutItemsSorted=true) and
normalizes arbitrary input otherwise; onBlock items are generated as their own
sorted run and merged in the same way.
~14-20x faster on realistic buffers (see packages/envio/bench). Adds a
mergeIntoBuffer correctness test.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
* Address review: drop bench, single onBlock merge, simplify test helper
- Delete the standalone benchmark script.
- updateInternal now folds onBlock items into the buffer with a single merge at
the end instead of merging mid-function; block items stay their own sorted run
so the merge remains linear.
- makeInitialWithOnBlock returns the fetch state directly (indexing addresses
were unused by every caller).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Replace water-fill budget algorithm with greedy fromBlock-sorted pass (#1415)
* Cap open-ended probe fan-out in the fetch water-fill
When the fresh per-tick budget is thin relative to the number of
partitions, the water-fill split gives each partition a sub-item
allotment that the open-ended emit floors to a 1-item query, so a
single tick fires a burst of near-empty probes and overshoots the
budget.
Concentrate instead: serve only the neediest
ceil(rangeItemsTarget / minQueryItems) probe partitions this tick, each
taking a full ~minQueryItems-sized probe, and let the rest wait until
freed reservations grow the budget. Chunk partitions self-limit via
density-sized chunks and are never capped, so normal fan-out and
post-rollback resume are untouched.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Keqij8JHea79B2rqJX4ApZ
* Select fetch queries by fromBlock against a chain budget
Replace the per-partition water-fill (and the earlier probe-fan-out cap)
with a single budget pass:
1. Generate every candidate query for the tick with no budget check —
gap-fill holes, plus each in-range partition's density-sized chunks or,
for an unknown-density partition, one open-ended probe sized to its even
share of the fresh budget (freshBudget / inRangeCount).
2. Sort all candidates by fromBlock.
3. Accept them in that order while the budget (chainTargetItems minus
in-flight reservations) stays positive; the query that tips it negative
is still accepted, everything after it waits for a later tick.
Selecting by fromBlock spends the budget on the earliest blocks across all
partitions first, so the frontier advances evenly and no partition is
starved by iteration order — and gap-fill, chunks, and probes all stop
together once the budget is spent. Removes waterLevel and the minQueryItems
cap.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Keqij8JHea79B2rqJX4ApZ
* Size open-ended probes by chain density over the range to the target
An open-ended probe now reserves chainDensity × (chainTargetBlock −
fromBlock + 1) / partitionCount — the events its range to the target is
expected to hold, split across partitions — instead of an even share of
the fresh budget. ChainState passes its effectiveDensity down for this.
When the chain has no density signal, or the partition is already at the
target (no range), it falls back to the even budget share so cold chains
and caught-up partitions still probe.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Keqij8JHea79B2rqJX4ApZ
* Size probes by budget-implied density over the in-range coverage
Replace the passed-in chainDensity with a rangeTargetDensity derived
inside getNextQuery: freshBudget / (chainTargetBlock − frontierCursor + 1),
where frontierCursor is the furthest-behind in-range cursor. A probe then
reserves rangeTargetDensity × (chainTargetBlock − fromBlock + 1) /
inRangeCount, so a partition covering less of the range to the target (it
sits further ahead) gets proportionally fewer items, while the furthest-
behind partition gets the full even share.
Measuring the range from the in-range frontier (not the chain buffer
frontier) keeps a lone in-range partition on the full budget instead of
having it diluted by out-of-range laggards, and drops the chainDensity
parameter ChainState was threading down.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Keqij8JHea79B2rqJX4ApZ
* Optimize greedy budget pass: fewer sweeps, bounded generation (#1418)
- Fold the chainReserved sum and partitionIndexById build into the
Phase A partition sweep (3 full passes over partitions -> 1).
- Cap per-partition chunk generation at the fresh budget: a partition
can be accepted at most the budget plus one overshoot, so further
chunks can never be accepted. Shrinks the candidate set and sort cost
when the budget is small relative to the pending-chunk cap.
- Acceptance pass: sort candidates in place and stop at the first
candidate that can't be accepted, instead of copying via toSorted and
scanning the whole tail with forEach.
- Hoist the loop-invariant chunk-start ceiling out of the chunk loop.
- Rename waterFillState -> partitionFillState (no water-fill left).
Claude-Session: https://claude.ai/code/session_01Cj7fN5nh9d2rLeWAXnD1d5
Co-authored-by: Claude <noreply@anthropic.com>
* Fix budget deadlock when gap-fill precedes returned query (#1419)
* Let gap fills bypass the fresh-budget gate
A gap-fill candidate was gated on the fresh forward-progress budget, so a
partition could deadlock after a partial/out-of-order chunk: chunk [101,200]
returns and lingers in mutPendingQueries behind an unfilled [51,100] hole,
its reservation already released by ChainState, yet the FetchState budget
sweep still counted it — driving freshBudget to 0 and dropping the [51,100]
gap-fill every tick, so the returned query could never be consumed.
Fix by budgeting acceptance against the full chainTargetItems and reserving
in-flight queries per-query in fromBlock order: a gap-fill, whose fromBlock
precedes the query it unblocks, claims budget ahead of that reservation.
Returned-but-unconsumed queries (fetchedBlock set) no longer count toward the
budget, matching the release ChainState already performed.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S6hp9FfBBT5insJwt2e28F
* Charge same-block reservations before fresh candidates
On a fromBlock tie, order in-flight reservations ahead of fresh candidates in
the acceptance stream. A same-block candidate could otherwise be emitted while
the pool budget was already exhausted (chainTargetItems still carrying
pendingBudget), pushing total reserved work past the target buffer. Only a
strictly-earlier candidate — a gap-fill preceding the query it unblocks —
should borrow ahead of a reservation.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S6hp9FfBBT5insJwt2e28F
---------
Co-authored-by: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Separate event density from source range capacity (#1423)
* Separate and smooth per-partition event density (#1426)
* Separate event density from source range capacity
* Enable strict warning checks in ReScript configurations (#1424)
* Treat ReScript warning 23 as an error in indexer configs
Promote the "useless record with clause" warning to an error in the
generated-project template and the test scenarios. The envio runtime
package already errors on all warnings via "+a".
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DGX7HGV5nCwFHHoazo8dCM
* Enforce all ReScript warnings as errors in test scenarios
Set warnings.error to "+a" for the test_codegen, fuel_test, and svm_test
scenarios, matching the envio runtime package. Leave the user-facing
generated-project template without a warnings override.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DGX7HGV5nCwFHHoazo8dCM
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Smooth per-partition event density
* Fix strict ReScript warnings after main merge
* Trust event density independently from source capacity
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Fix reorg-threshold cross-chain query stall (#1430)
* Add PIN test reproducing the below-head chain silence stall
Reverts the earlier fix and exploratory tests and pins the exact production
stall on the unfixed scheduler: when one chain falls far behind and its query
reservation drains the shared fetch-buffer budget, a chain below its own head
but starved of budget emits no query and (being below head) won't wait for a new
block, so getNextQuery returns NothingToQuery. checkAndFetch never dispatches
NothingToQuery, so that chain stops querying AND stops polling getHeightOrThrow
and goes silent.
The test asserts the correct behavior — the starved below-head follower keeps
polling getHeightOrThrow. It is RED on this unfixed scheduler (the follower never
re-polls) and turns green once below-head chains are dispatched as
WaitingForNewBlock instead of being dropped (the "Keep below-head chains polling"
change). Verified red without the change and green with it.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VhitjdvBNbfY6tRnv6RQcw
* Fix reorg-threshold cross-chain query stall
* Deduplicate fetch progress calculation
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Add minimum query admission budget (#1429)
* Add minimum query admission budget
* Keep block waiters outside query admission
* Keep block waiting in query selection
* Pause all chain actions below admission floor
* Anchor cross-chain alignment to most-behind chain's frontier (#1434)
* Anchor cross-chain alignment line at the most-behind chain's frontier
The waterfall's alignment line was only established on ticks where the
most-behind chain itself emitted a fresh query and had a density signal.
While that chain's queries were in flight (or it was still cold), every
other chain fetched unclamped to its own head, defeating the cross-chain
ordering the line exists for.
- Derive the line from the most-behind known-height chain's fetch-frontier
progress before dispatching, so it hol…
* fix: parse SVM accountFilters as array of AND-groups in public config (#1408)
The CLI emits accountFilters as Vec<Vec<SvmAccountFilterJson>> (AND-groups
OR-ed together, normalized from both the flat and any_of YAML shapes), and
the consumer in Config.fromPublic already maps it as nested groups. The
parse schema declared a flat array, so any SVM config using account_filters
failed to load with:
Invalid indexer config: Failed parsing at ["svm"]["programs"][...]
["accountFilters"]["0"]["position"]. Reason: Expected int32,
received undefined
Wrap the schema in one more S.array so it matches what the CLI emits and
what the consumer expects, and add a regression test.
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* Move EVM event routing, decoding, and query construction to Rust (#1404)
* Move EVM event routing and decoding to the Rust clients
Give each onEventRegistration a chain-scoped sequential id (its index in
the chain's onEventRegistrations array) and pass the registrations -
id, isWildcard, sighash/topicCount, param metadata - into the Rust
EvmHypersyncClient and EvmRpcClient constructors. Rust now routes every
log to its registration (owning contract via the partition's
address -> contract-name index, wildcard fallback) before decoding:
- DecoderCore keys a per-MetaKey router (by_contract_name + wildcard)
and decodes with only the routed variant's param names, so items carry
flat params instead of a per-contract dict.
- get_event_items and getNextPage take the partition's
contractNameByAddress; items return onEventRegistrationId and logs
that route nowhere are dropped on the Rust side.
- The RPC client normalizes log addresses (lowercase/checksum) so they
match the routing index and the JS address type directly.
- ReScript sources resolve items with
onEventRegistrations[item.onEventRegistrationId]; EventRouter's EVM
half (getEvmEventId, fromEvmEventModsOrThrow) is deleted and
EvmChain.makeSources enforces the id = array index invariant.
- Registration-time duplicate/wildcard-collision validation is mirrored
as a backstop in the Rust decoder constructor.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0145w9f63kqQmFf7mWMDWmQc
* Make onEventRegistration.id immutable
id is derived purely from push order — assign it via record spread when
the registration lands in the chain's array (HandlerRegister.finishRegistration,
EvmChain.makeSources) instead of mutating an existing field.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0145w9f63kqQmFf7mWMDWmQc
* Move EVM query construction to the Rust clients
Pass the full per-(event, chain) registration to the Rust clients at
construction — EventParamsInput becomes EventRegistrationInput, gaining
dependsOnAddresses, the resolvedWhere topic selections (per-topic
Option<Vec<String>>, None = contract-addresses marker), and the
selected block/transaction field lists. A shared SelectionBuilder
(evm_hypersync_source/selection.rs) owns everything a query derives
from the partition's selection and current addresses:
- log selections: address-free pooling + topic0 compression,
per-contract address scoping, wildcard-by-address marker expansion
into lowercase padded address topics, in registration order so query
bytes stay stable for caching;
- HyperSync field selection: union over the selection's registrations
with the transactionIndex exclusion, plus the forced required fields;
- the address -> contract-name routing index, derived from the
partition's addressesByContractName instead of being passed
separately.
The napi query surface shrinks to the block range plus the partition's
registration ids and addressesByContractName: get_event_items takes an
EventItemsQuery and builds the HyperSync query internally; get_next_page
drops log_selections/contract_name_by_address for registration_ids/
addresses_by_contract_name. Both clients expose build_log_selections
for tests and debugging.
On the ReScript side the per-source getSelectionConfig machinery
(bucketing, materialization, WeakMap memoization) is deleted from
HyperSyncSource and RpcSource; sources just forward selection ids and
addresses. LogSelection keeps only parseWhereOrThrow and the
materialize helpers used by tests; Rpc.GetLogs drops the topic-query
types. JS selection-shape tests are rewritten against
buildLogSelections, and field-selection behavior is covered by Rust
unit tests. Mock registrations now need hex-decodable sighashes since
the client validates them at construction.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0145w9f63kqQmFf7mWMDWmQc
* Store onEventRegistrationIndex on items; resolve registrations via ChainState
Internal.item's Event variant now carries onEventRegistrationIndex (the
registration's chain-scoped array position, renamed from id) instead of
the registration object, so Rust-built items can be final and complete.
The full registration is resolved through the chain's registration
array: stored on ChainState.t and mirrored in a per-chain registry in
Internal (setOnEventRegistrations at chain-state startup,
addOnEventRegistration for simulate/test setups that synthesize items,
getItemOnEventRegistration for consumers without a chain state at hand
— ecosystem toRawEvent/toEventLogger, FetchState's clientAddressFilter,
ChainFetching, EventProcessing, batch materialization).
Simulate appends its synthetic registrations into the run's
registrationsByChainId chain arrays (the same arrays chain-state startup
installs) instead of a side registry, so item indexes stay valid after
startup replaces the per-chain entry.
Rename the napi surface to match: EventRegistrationInput.index,
registration_indexes on both query params, on_event_registration_index
on items.
Drop the parallel eventRegistrations option on HyperSyncSource/RpcSource
— the Rust registration inputs are now derived inside the sources from
onEventRegistrations via HyperSyncClient.Registration.
fromOnEventRegistrations (moved from EvmChain), removing a second field
that had to stay in lockstep with the lookup array.
Fix indexed dynamic-type event filters: tuple/array where values were
passed through raw (previously latent — they only crossed napi at query
time and never in tests; passing registrations at client construction
surfaced it as a startup failure). Encode them as keccak256 of the ABI
encoding like the chain does, trying a directly-passed tuple as one
value before falling back to an OR-list of tuples.
Remove dead code (Rust add_field/ensure_required_log_fields/
TopicSelection::has_filters, ReScript QueryTypes topic helpers) and
refactor-narration comments.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0145w9f63kqQmFf7mWMDWmQc
* Rename EventRegistrationInput to OnEventRegistration; clarify decoder field names
Match the ReScript-side naming for the registration crossing the napi
boundary, and make the decoder's routing fields say what they hold:
EventVariant.on_event_registration_index, RegisteredEvent.
wildcard_variant_idx / variant_idx_by_contract_name.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0145w9f63kqQmFf7mWMDWmQc
* Fix event registration ownership and indexed topic encoding (#1412)
* Fix event registration ownership and topic encoding
* Allow empty standalone mock source responses
* Store registration state on mock sources
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Replace test-only log selection API with E2E coverage (#1413)
* Add RPC source contract pin framework (#1416)
* Centralize config parsing tests around YAML (#1421)
* Centralize config parsing tests around YAML
* Explain SVM pubkey validation dependency
* Include licenses directory in published envio package (#1422)
* Fix incorrect license in envio package.json
The published envio package declared GPL-3.0, but the project ships a
proprietary SaaS EULA (licenses/LICENSE.md), not a GPL license. Mark the
package UNLICENSED to reflect its proprietary terms.
* Ship the EULA and reference it from the license field
The envio package is proprietary (licenses/LICENSE.md is a SaaS EULA), so
use the standard 'SEE LICENSE IN LICENSE.md' form instead of UNLICENSED, and
copy the EULA to the published package root so the reference resolves for
consumers. Add LICENSE.md to the artifact verifier's required files.
* Ship the full licenses directory with the envio package
The licenses/ dir holds four files: the HyperIndex software EULA (EULA.md),
the SaaS EULA (LICENSE.md), the CLA, and an overview README. The npm package
is the HyperIndex software, so point the license field at licenses/EULA.md and
copy the whole directory into the published package. Add 'licenses' to the
files allowlist (npm only force-includes a root LICENSE, not a subdirectory)
and verify every license file ships.
* Point license field at the licenses overview README
licenses/README.md is the licensing index: it explains which terms apply to
the software, generated code, and hosted service, and links the specific
EULAs. Reference it from the license field so consumers land on the overview
rather than a single EULA that only covers part of the picture.
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Enable strict warning checks in ReScript configurations (#1424)
* Treat ReScript warning 23 as an error in indexer configs
Promote the "useless record with clause" warning to an error in the
generated-project template and the test scenarios. The envio runtime
package already errors on all warnings via "+a".
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DGX7HGV5nCwFHHoazo8dCM
* Enforce all ReScript warnings as errors in test scenarios
Set warnings.error to "+a" for the test_codegen, fuel_test, and svm_test
scenarios, matching the envio runtime package. Leave the user-facing
generated-project template without a warnings override.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DGX7HGV5nCwFHHoazo8dCM
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Improve rollback logging and conditional event registration logging (#1425)
* Improve indexer logs for contract-register events and rollback range
Omit numContractRegisterEvents from the "Finished querying" log when it's
zero, and log the per-chain rollback block range for all affected chains
at info level so reorg rollbacks aren't limited to the reorg chain's
target block.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xvxwf6mi6rT2AV16sx2KSL
* Emit per-chain rollback logs and quiet the batch-wait log
Drop the "Waiting for batch..." log to trace, remove the aggregate
"Rolled back chains on reorg" log, and replace the trace-level "Finished
rollback on reorg" log with a per-chain info "Rollbacked" log carrying the
chain id, from/to block range, rolled-back event count, and reorg-chain
flag.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xvxwf6mi6rT2AV16sx2KSL
* Split rollback entity changes into a separate trace log
Restore the entity deleted/upserted detail as its own trace-level log and
drop the isReorgChain field from the per-chain "Rollbacked" info log.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xvxwf6mi6rT2AV16sx2KSL
* Avoid chainId binding collision on rollback logs
Build the rollback logger without inheriting the reorg chain's logger,
which bound its chainId onto every line and collided with the per-chain
chainId on the "Rollbacked" logs. The reorg chain is identified by the
reorgChain param instead.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Xvxwf6mi6rT2AV16sx2KSL
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Extract client-side address filtering from FetchState (#1414) (#1427)
* Filter over-fetched events before contract registration
Over-fetched events (a merged partition returning an address before its
effectiveStartBlock, or a wildcard param referencing an address registered
after the log's block) were running their contractRegister handlers and
spawning dynamic contracts before being dropped from the buffer.
Apply the client-side address filter to the contract-register set before
running the handlers. Extract the predicate as FetchState.filterByClientAddress
and expose it through ChainState so ChainFetching can gate registration; the
buffer is still filtered after registration in handleQueryResult, so events
referencing a contract registered in the same batch keep routing to handlers.
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
* Move client address filter fully before contract registration
Follow-up to the previous commit: instead of only gating the contract-register
set, apply the client-side address filter to the whole response up front, so an
over-fetched event neither spawns dynamic contracts nor enters the buffer.
This is only correct if a non-wildcard event for an address registered in the
same batch can't appear before its registration — which a real backend
guarantees, since a query only returns logs for the addresses it was sent. The
simulate source didn't model that (it dumped every item on the first call), so
make it faithful: return only items matching the query's block range, selection,
and (for non-wildcard events) address set, delivering each once; wildcards are
over-fetched for the client filter to gate, mirroring HyperSync. A contract
registered mid-run now surfaces its events in the follow-up query the
registration triggers, exactly as in production.
Parse simulate items at the process's startBlock (not the config default) so
they land in the range the source is queried over. The dead-input tracker stays
downstream, observing processed batches, so it still reports items excluded by
any filter.
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
* Merge buffer with a single sort-free pass instead of re-sorting
Buffer accumulation re-sorted the whole buffer on every response via
Array.sort(compareBufferItem) — an O(n log n) pass whose comparator crosses the
JS↔native boundary on each comparison — plus a Set of string keys for dedup.
Replace it with mergeIntoBuffer: the buffer is already sorted, so insertion-sort
just the (small, usually ascending) response and merge the two runs in one linear
pass, dropping duplicates as adjacent-equal. Comparison is inlined
(compareBufferItem now returns an int with explicit field compares and a
registration-index tiebreaker) with no Array.sort callback and no allocated key.
updateInternal assumes a sorted buffer (hot paths pass mutItemsSorted=true) and
normalizes arbitrary input otherwise; onBlock items are generated as their own
sorted run and merged in the same way.
~14-20x faster on realistic buffers (see packages/envio/bench). Adds a
mergeIntoBuffer correctness test.
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
* Address review: drop bench, single onBlock merge, simplify test helper
- Delete the standalone benchmark script.
- updateInternal now folds onBlock items into the buffer with a single merge at
the end instead of merging mid-function; block items stay their own sorted run
so the merge remains linear.
- makeInitialWithOnBlock returns the fetch state directly (indexing addresses
were unused by every caller).
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
---------
Co-authored-by: Claude <noreply@anthropic.com>
* SVM: exclude failed-transaction instructions (#1428)
HyperSync serves instructions from failed Solana transactions and the
runtime delivered all of them to onInstruction handlers, silently
over-counting (~18% for SPL TransferChecked over the sampled slots).
Exclude instructions whose parent transaction did not commit, matching
EVM (reverted-tx logs never exist) and the old RPC `!tx.meta.err` pattern.
Filter client-side in SvmHyperSyncSource.getItemsOrThrow on the
`isCommitted` flag HyperSync already delivers on every instruction row (a
required column, zero extra bandwidth). The current query API cannot push
this down (InstructionSelection exposes only `is_inner`; instruction and
transaction selections union at block level rather than joining), so the
client-side check stands until HyperSync adds a server-side `is_committed`
predicate, at which point it becomes a redundant safety net.
No opt-in knob for now: keep the surface minimal and add a config option
(e.g. per-instruction `include_failed`) if and when someone needs failed
transactions. Deferring it also leaves the opt-in design open rather than
committing to a config shape prematurely.
HOS-1610
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Dmitry Zakharov <dzakh.dev@gmail.com>
* Fix rollback handling for deleted entities (#1431)
* Fix rollback handling for deleted entities
* Return rollback removed IDs directly
* Harden rollback test error handling
* Add Tron chain to fix hypersync health check (#1436)
Tron (chain_id 728126428) is served publicly by the HyperSync API but was
missing from the Network enum, causing the health check to fail.
Claude-Session: https://claude.ai/code/session_011GxCWhUKxvdy8zgg44wvMr
Co-authored-by: Claude <noreply@anthropic.com>
* Add per-chain effect caching and rate limiting (#1432)
* feat(effects): per-chain cache scoping via crossChain option
Add a `crossChain` option to the Effect API (defaults to `true`). When
`crossChain: false`, an effect's cache and rate-limit window are isolated
per chain and the handler can read `context.chain.id`.
- Public API: `crossChain?: boolean` on effect options; required
`context.chain.id` in ReScript and TypeScript types. Reading
`context.chain` on a cross-chain effect throws a guiding error.
- Scope model (`CrossChain | Chain(int)`) resolved from the effect config
and the current handler chain. Nested calls follow: handler -> either;
chain -> either; cross-chain -> cross-chain; cross-chain -> chain fails
before cache lookup with both effect names and remediation.
- Per-scope runtime boundary: in-memory cache, in-flight dedup, rate-limit
window/queue and active-call state are keyed by the resolved cache
address; the canonical input key is unchanged.
- Central reversible mapping `Internal.EffectCache` between
(effectName, scope) <-> table name <-> cache file path, used everywhere
instead of prefix slicing. Cache metadata is keyed by the full address.
- Postgres: cross-chain tables `envio_effect_<name>`, chain-scoped
`envio_<chainId>_effect_<name>`; discovery matches both formats.
`.envio/cache` gains numeric per-chain subdirectories; restore rejects
malformed chain directories and supports one directory level; dump does
the exact reverse mapping.
Tests: address round trips / legacy / coexistence / invalid parsing,
per-chain dedup and independent rate limits, cross-chain sharing, and an
E2E covering context.chain.id, the guiding errors, and per-chain
persistence.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* refactor(effects): unboxed effectScope, enumerable chain getter, exact error tests
Address review feedback:
- Make `context.chain` an enumerable own getter closing over the resolved
chain, dropping the hidden `_chainId`/`_effectName` instance fields.
- Mark `effectScope` `@unboxed` (CrossChain -> "crossChain", Chain(id) ->
the raw id, discriminated by runtime type).
- Assert the exact cross-chain `context.chain` and nested cross-chain ->
chain-scoped error messages in the E2E test.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* refactor(effects): address review — generic chainScope, resolved-table write path, prototype getter
- Rename `effectScope` -> `chainScope` (generic; reused for entities later).
- Persistence write path no longer threads effect+scope: `updatedEffectCache`
and `setEffectCacheOrThrow` take the resolved `table` (the cache address) +
item schema. The in-mem table now holds its built `table`, so the address is
resolved once in `getEffectInMemTable` and reused by load/snapshot/write.
- Move the `context.chain` getter back onto the prototype (enumerable, like
`log`), reading per-instance non-enumerable fields.
- Collapse the two MockIndexer cache-query helpers into one
`queryEffectCache(effect, ~scope=?)`.
- Tighten the crossChain docs: concise and user-facing, no table/file internals.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* Add scope label to per-scope effect gauges and strict chain-id parsing (#1435)
The envio_effect_active_calls, envio_effect_cache, and envio_effect_queue
gauges are backed by per-scope state since caching became chain-scoped, so
scopes of the same effect clobbered each other's value. Label them with
scope: "crossChain" | <chain id>.
Cache directory chain ids are now parsed strictly: "1foo" and "007" are
rejected instead of being treated as chains 1 and 7 via parseInt semantics.
Claude-Session: https://claude.ai/code/session_011YLPufR6wf9LYFAsNjKz1t
Co-authored-by: Claude <noreply@anthropic.com>
* fix(effects): validate effect names and guard cache-table discovery by columns
Two review points not covered by #1435:
- Validate effect names to `[A-Za-z0-9_-]+` in createEffect. The name is used
as a cache table name and a .envio/cache path segment, so path separators and
traversal (`a/b`, `../evil`) must be rejected to keep the
(name, scope) <-> table <-> path mapping reversible.
- Cache-table discovery now also requires the effect-cache column shape
(exactly `id` + `output`), so a user entity table that matches the reserved
name pattern is never mistaken for an effect cache.
#1435 already addressed the per-scope metric-gauge clobbering (via a scope
label) and strict chain-id parsing, so those are not duplicated here.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* fix(effects): preserve rate-limit budget across rollbacks; guard cache table length
- Rate-limit windows lived on the per-scope effect in-mem table, which a reorg
wipes (beginRollbackDiff clears state.effects), refilling the budget on
replay. Keep them in a survivor dict on IndexerState (not cleared on
rollback), keyed by cache table name; each recreated in-mem table reuses the
same window. Rate limiting reflects real API throughput, not indexing
progress. + regression test.
- Reject effect cache table names longer than PostgreSQL's 63-char identifier
limit in makeCacheTable, instead of letting PG silently truncate and diverge
from what cache discovery reads back.
- Make the per-chain rate-limit test assert that chain 2 bypasses chain 1's
queue (order) rather than relying on which call resolves first.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* revert(effects): drop the 63-char cache table name guard
An effect name long enough to overflow the scoped identifier is unrealistic;
the guard isn't worth the runtime throw.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* refactor(effects): encapsulate effect state in an EffectState module
Effect runtime state was two loose dicts on IndexerState with divergent
rollback lifecycles (cache wiped by beginRollbackDiff, rate-limit windows
deliberately kept), an invariant that lived only in a comment.
Introduce a nested IndexerState.EffectState module (mirroring EntityTables)
that owns both maps and exposes getTable / forEach / resetForRollback. The
rollback semantics — drop cache tables, preserve rate-limit windows — are now
enforced by resetForRollback rather than remembered. Not folded into
ChainState/CrossChainState: effect state is keyed by (effect, scope) and
cross-chain effects have no chain, so it's a separate concern from chain
fetch/coordination state.
Behavior-preserving: InMemoryStore.getEffectInMemTable and Writing now delegate
to the module; all effect/rollback tests pass unchanged.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* refactor(effects): address review — extract EffectState, constructor chain field, required scope
- Move the EffectState module out of IndexerState into its own EffectState.res
/ .resi file.
- context.chain: install it in the EffectContext constructor instead of a
prototype getter — a plain data field `{ id }` for chain-scoped effects (no
getter), and only cross-chain contexts install a shared top-level throwing
getter (created once, not per context).
- MockIndexer.queryEffectCache: make the `~scope` argument required; pass it
explicitly at all call sites.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* docs(effects): drop redundant rateLimitState comment
The option type already conveys "None when the effect has no rate limit".
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* fix(effects): scope effect-call timing metrics per chain
prevCallStartTimerRef and active-call state moved per (effect, scope),
but the call_seconds/call_seconds_total/call_total counters were still
keyed by effect only. Overlapping calls on different chains double-counted
wall time into one series. Give these counters the same {effect, scope}
labels as the active-calls gauge so each scope tracks its own throughput.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
* fix(effects): allow dots in effect names
The name-validation regex rejected existing safe names like "token.metadata".
Dots round-trip fine through the (name, scope) <-> table <-> path mapping
(table names are quoted; the cache scanner strips only the ".tsv" suffix).
Allow dots mid-name while still excluding path separators and forbidding a
leading dot, so a name can never be "." / ".." or traverse out of the cache dir.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Replace prune throttler with smart scheduling in write loop (#1444)
* Fix history prune racing batch writes and losing rollback anchors
The stale-history prune ran on its own throttler concurrently with batch
writes. Its anchor deletion relies on "no history after the safe
checkpoint", which a concurrently committing batch falsifies: the batch's
backfill sees the anchor and skips, the prune sees no post-safe rows and
deletes the anchor, and after both commit the entity has history only
above the safe checkpoint. A later rollback then deletes the entity
instead of restoring it.
Move pruning into the write loop so it can never overlap a history write
for the same entity:
- Each write picks up to 5 pg entities not pruned for the prune interval,
excluding entities written in the batch (rollback writes touch every
history table, so they get none), and prunes them one at a time
concurrently with the batch write, awaited before the next write.
- Entities starved of the concurrent prune (eg written in every batch)
are force-pruned sequentially right after the write, once they haven't
been pruned for 5x the interval.
- Prune failures are logged instead of failing the write loop.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UjkHvbFKZxk1L3JY6e7HCt
* Select prune targets in a single pass over entities
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UjkHvbFKZxk1L3JY6e7HCt
* Throttle failed prune retries and keep checkpoint pruning out of rollback writes
Record the prune attempt time on failure too, so a failing entity retries
on the prune interval instead of on every write. Run checkpoint pruning
only alongside a concurrent entity prune; when nothing runs concurrently
(eg a rollback write) it moves to the forced phase after the write.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UjkHvbFKZxk1L3JY6e7HCt
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Refactor query sizing to water-fill budget across chains (#1392)
* Make multichain fetch scheduling chain-controlled
Replace the per-partition/per-query greedy admission scheduler with a
per-chain waterfall: CrossChainState.checkAndFetch visits chains
furthest-behind first, handing each its remaining share of the shared
buffer budget. ChainState turns that budget into a soft target block
using a new chain-wide event density (seeded from cumulative progress,
smoothed with an EMA per batch), and FetchState.getNextQuery sizes
known-density partitions against that target block while splitting
whatever budget is left across partitions with unknown density.
This concentrates fetch effort on the bottleneck chain per tick instead
of scattering a shared item budget across every chain's full candidate
query set.
* Fix probe-split eligibility and query ordering in FetchState.getNextQuery
The unknown-density probe split counted partitions with nothing left to
query (already at their endBlock/mergeBlock/knownHeight ceiling), inflating
the divisor and under-sizing eligible partitions' queries. Add a
hasEligibleRange check mirroring pushQueriesForRange's own gate to exclude
them.
Splitting partitions into known/unknown passes also broke the original
idsInAscOrder query ordering that several tests assert on positionally;
restore it by sorting the final query list back into partition order.
Update FetchState_test.res fixtures accordingly, including a case that
needed distinct expected values across three eligibility scenarios that
previously shared one fixture.
* Redesign FetchState.getNextQuery as an even per-partition water-fill
Query creation now splits the chain's range budget evenly across
in-range partitions each round, rather than sizing every known-density
partition against the full chain target while unknown-density
partitions fought over the leftover. A partition already holding more
budget than its even share (e.g. from an earlier tick's in-flight
query) sits out a round so its share flows to the others, and the
split is recomputed each round against the shrinking set of partitions
still needing more.
Also:
- Rename estResponseSize -> itemsTarget throughout, since the field is
now both the server-side maxNumLogs-style cap and the budget
reservation/consumption unit, not just an estimate.
- Bucket queries by partition index as they're created instead of
sorting the whole result at the end of every tick.
- Only trust a partition's density once it has two responses
(matching the existing chunking-heuristic gate); a single response
is too noisy to size the next query from.
- Smooth the chain-wide density EMA as (old + new) / 2 instead of
(2*old + new) / 3.
* Address review feedback on the water-fill scheduler: dedupe reserved-sum
walk, tighten round bound, add coverage
- getNextQuery walked every partition's mutPendingQueries twice (once
for chainReserved, again to seed reservedByPartition per partition).
Merge into a single pass.
- Replace the unproven roundsRef < 1000 safety cap with a provable
bound: every active partition either finishes or advances its chunk
count each round, capped at maxPendingChunksPerPartition, and all
active partitions progress in lockstep (not one at a time), so no
partition can outlive maxPendingChunksPerPartition + 1 rounds.
- Add ChainState_test.res covering the chain density seed (from
resumed progress) and the EMA blend.
- Add a CrossChainState_test.res case pinning the waterfall's actual
cross-chain budget flow: a chain whose real range caps its
consumption below its share leaves the remainder for the next chain.
* Make the water-fill round's per-partition share order-independent
Each round computed ipb = rangeBudget/n once, but then capped every
partition's actual budget at min(rangeBudget, ipb - reserved) and
decremented rangeBudget after each partition — so a partition
processed earlier in the same round (e.g. one forced to overshoot its
share via the "at least one full chunk" rule) shrank the pool for
whoever came after it. Same reservations, different iteration order,
different split (and total consumption could even exceed rangeBudget
depending on order).
Fix: every partition's share for a round is ipb - reserved, fixed for
the whole round; rangeBudget is only re-derived once, from the round's
actual total consumption, after every partition has had its fixed
shot. A partition can still overshoot its own share, but it can no
longer steal from another partition in the same round.
Also fixes a SourceManager_test.res assertion that was pinned to the
old order-dependent rounding artifact (three identical partitions
splitting a budget three ways used to get 16667/16667/16666; they now
all get 16667, as they should since they're indistinguishable).
* Redistribute a filled partition's leftover budget in the water-fill (#1394)
The per-partition round budget was `ipb - reserved`, where `ipb` was an
even share of only the *remaining fresh* budget (`rangeBudget / n`) while
`reserved` accumulated each partition's full footprint (existing in-flight
+ gap-fill + this call's prior-round emissions). Those two are on different
scales, so once a chunked partition's running reservation passed a later
round's fresh share, `ipb - reserved` went negative and the partition was
dropped — leaving budget unspent even though it still had range to fetch
and a sibling had just freed its share by filling early.
Compute the round's level as a real water-fill line — (remaining fresh
budget + the still-not-filled partitions' current footprint) / count —
and top each partition up toward it. A partition already above the line
gets nothing (its head start is its whole share); the rest absorb the
leftover, so the budget is fully used and per-partition totals stay even.
The loop now runs until either the not-filled set drains or the whole
fresh budget is reserved, dropping the redundant round cap: a partition
survives a round only by advancing chunksUsedThisCall (bounded by
maxPendingChunksPerPartition) or consuming budget, so it terminates on
its own.
Add a regression test: a range-capped partition and a deep partition
splitting a 900-item budget — the deep one now absorbs the capped one's
freed share (4 chunks / 720 items) instead of stopping at 2.
Claude-Session: https://claude.ai/code/session_0134TTgxQ3ci5mWUnt928yr9
Co-authored-by: Claude <noreply@anthropic.com>
* Cap unknown-density probe query at maxItemsTarget
An unknown-density partition's open-ended probe was sized to its full even
share of the chain's budget with no ceiling. When such a chain leads the
furthest-behind waterfall, that share is the entire cross-chain buffer pool,
so its single probe consumed 100% of the remaining budget and starved any
sibling chain needing its own first probe in the same tick (e.g. multiple
chains entering the reorg threshold together).
Cap the probe at maxItemsTarget (10_000), restoring the old bounded-default
ceiling. The leftover budget flows to the next chain via checkAndFetch's
remaining subtraction, exactly as before.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GBSAcMXTNy2K8i16bkJELo
* Don't seed chain density from a zero-event batch
The resume-seed path only sets chainDensity once numEventsProcessed > 0, but
the per-batch EMA update seeded Some(0.) after any progress-only batch (blocks
advanced, no events), contradicting that documented behavior and making the
first real batch blend against 0 instead of seeding from its own density.
Guard the EMA seed on the batch having events, matching the resume path. The
Some(oldDensity) blend is unchanged.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GBSAcMXTNy2K8i16bkJELo
* Adjust itemsTarget setting logic
* Enforce reservation == server cap and stop chunking without trusted density
- Floor itemsTarget at 1 at creation (densityItemsTarget, water-fill chunk
loop, probe) so a query's budget reservation always equals the
maxNumLogs-style cap sent to the server; drop SourceManager's 2000-item
fallback that let density-0 queries return up to 2000 unaccounted items.
- Emit density-priced chunks only for a trusted positive density; density-0
and unknown-density partitions get a single open-ended probe sized at the
even split of the tick's fresh budget (maxItemsTarget cap removed). This
removes the chunkCost=0 path that flooded 10 free hard-bounded chunks per
partition and froze the 1.8x range growth.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Extract getTrustedDensity helper for water-fill chunk sizing
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Make query itemsTarget an int and trim redundant comments
The ceil-to-int conversion now happens once at query creation, so the
reservation, the budget accounting, and the server cap all use the same
integer value; SourceManager passes it through untouched.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Price gap-fill by trusted density with available-density fallback
Gap queries now use getTrustedDensity: chunks only on a trusted positive
density (same rule as the water-fill); a trusted-zero density prices the
whole gap as one open query, and a partition with no density signal prices
it by available density — its equal-divide budget spread over the remaining
range this tick — so a small gap reserves proportionally little instead of
a noisy one-sample estimate or a NaN from dividing by a zero range.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Cap follower chains at the leader's target progress in the waterfall
Chains beyond the most-behind one in the budget waterfall are now capped
at that leader's target progress, mapped onto their own block range
(ChainState.progressAtBlock/blockAtProgress), so no chain runs further
ahead than the chain the shared buffer pool is prioritizing. A chain
visited after the pool is exhausted simply sits out the round — its
reservations release as responses land, so the next tick redistributes.
FetchState's dynamic-contract partition merge now inherits the sum of
its parents' trusted densities (weighted onto the merged partition's
min query range) instead of resetting to 0, so a merge with density
history doesn't regress to an unpriced probe.
Update E2E/rollback tests to the now-serialized cross-chain query
dispatch (most-behind chain queries first; siblings follow once its
response releases budget) and to give density-dependent chunking tests
a nonzero item count to trust.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Cap a clamped chain's fresh budget at its density-priced range cost
When a chain's target block is clamped (head, endBlock, or the
cross-chain alignment cap), a known-density chain's fresh budget is now
capped at density x clamped range (in-flight reservations stay on top so
they don't crowd out new partitions). The unused remainder stays in the
waterfall's pool and flows to the next chain in the same tick, instead
of being held by an oversized probe until the response lands.
This also removes the drain loop the infinite-reorg-loop test needed:
the non-reorg chain's post-rollback refetch now reserves only its real
range cost, so the reorg chain gets budget immediately.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Give head-bound queries 2x density headroom in the budget cap
A query clamped at the head sized exactly at density x range truncates at
the server cap whenever the range is slightly denser than the estimate,
forcing an immediate catch-up query for the last few blocks. Double the
range cost for head-bound targets so one query usually suffices; the
extra reservation releases as soon as the response lands.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Refine chain budget caps: endBlock ceiling, 5k probe cap, 3x head headroom
- targetBlock now clamps at endBlock (when below the head) via a shared
fetchCeiling helper, so endBlock'd chains stop sizing and aligning
against range they'll never fetch.
- A chain with no positive density signal caps its fresh budget at 5k,
so one unknown chain measuring its first responses no longer holds the
whole cross-chain pool.
- Head/endBlock-bound queries get 3x (was 2x) density headroom against
truncating at the server cap and needing a catch-up query.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Fix clippy::useless_borrows_in_formatting across cli package
Remove redundant & references in format!/anyhow! arguments flagged by
the CI-pinned clippy (rust 1.97). Pre-existing on the base branch,
unrelated to the SourceManager/waterfall changes in this PR — fixed
here since it was blocking cargo-test from going green.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
* Fix clippy::to_string_in_format_args exposed by the previous fix
Removing the redundant & in anyhow!'s self.id.to_string() surfaced a
second lint on the same line: ChainId (u64) already implements Display,
so .to_string() inside the format arg is itself redundant.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01McpcXkR3pPWfEcq4mCj9Sw
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Fix clippy useless_borrows_in_formatting errors blocking CI
main's cargo-test job started failing clippy (-D warnings) on pre-existing
code after a stable-toolchain drift (no rust-toolchain pin), unrelated to
this PR's scheduling changes but inherited via the origin/main merge.
Removed the redundant `&` in format!/anyhow! args across 6 files, and
dropped a now-also-flagged explicit .to_string() on a Display type in
validation.rs.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GBSAcMXTNy2K8i16bkJELo
* Pour water-fill budget at an exact level and tighten chain budget edges
- Replace the per-round mean line in FetchState.getNextQuery with an exact
water level (sum of top-ups equals the poured budget), so uneven in-flight
reservations can no longer inflate other partitions' allotments past the
fresh budget
- Size unknown-density probes by their water-fill allotment instead of a
fixed pre-round even split, so leftover budget reaches the partitions
without reservations instead of being stranded
- Gate the 3x head headroom on the chain having caught up once (isReady)
- Blend chain density weighted by the batch's block span instead of a flat
(old + new) / 2
- Clamp progressAtBlock at 0 for the initial -1 fetch frontier
- Skip chains with no known height in the cross-chain waterfall so they wait
for a block instead of setting a degenerate alignment line
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KvUhc8DhbxjGPEtHoDNThJ
* Shrink density blend window to 100 blocks
Small batches (a few blocks) should barely nudge the chain density estimate,
while anything spanning 100+ blocks is a trustworthy fresh sample.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KvUhc8DhbxjGPEtHoDNThJ
* Add chunk headroom multiplier for budget-aware query sizing (#1400)
* Add chunk itemsTarget headroom and budget-driven chunk emission
Chunk reservations now carry a headroom multiplier over the density
estimate (1.5x during backfill, 3x in realtime, chosen in
CrossChainState.checkAndFetch and threaded down to
FetchState.getNextQuery), so a denser-than-expected range doesn't
truncate at the server cap. Open-ended probes stay allotment-sized.
The emit loop replaces the precomputed chunkCost/affordable estimate
with per-chunk actual itemsTarget accounting: the first chunk always
emits full-size, subsequent chunks only while they fit the budget, and
the min-one-chunk force applies once per call instead of once per
water-fill round.
Cap-hit truncations (partial response with itemsCount >= itemsTarget)
no longer update the chunk range history — they reflect our own
reservation, not server capacity. Sub-cap partials still do.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KpFcYPn8UbQfaEfW6gjant
* Restore min-one-chunk per water-fill round
A leftover re-pour forces a full chunk again, so the budget never
strands on chunk quantization; the overshoot stays bounded at one
chunk per partition per round and self-corrects via the reported
reservations. Drops the per-call emittedThisCall bookkeeping.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KpFcYPn8UbQfaEfW6gjant
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Implement cold-chain targeting and density-aware query sizing (#1401)
* Contain queries to the chain target block and rework cold-start sizing
- No chunk or gap-fill query starts past chainTargetBlock; emitted chunks
keep their full span, with endBlock/mergeBlock staying the hard bounds.
Skipped gaps regenerate from the pending-walk and fill once the target
reaches them.
- A chain with no density signal targets frontier + coldTargetRange
(init 20k), doubling whenever it goes idle without producing a signal,
capped at the fetch ceiling. The cross-chain waterfall clamps a cold
chain to min(5k, targetBufferSize), replacing the internal probe clamp,
and a cold leader no longer sets the alignment line.
- Query sizing uses effectiveDensity = max(processing EMA, ready-buffer
density), so a dense buffer overrides a stale-low EMA and ready items
alone take a chain out of cold mode.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018CiEziFbVe1P3Y6iuyfT5Z
* Replace cold-window doubling with a fixed 20k range
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018CiEziFbVe1P3Y6iuyfT5Z
* Span ready-buffer density from the processing block number
The buffer is consumed at batch creation while committed progress only
catches up after the batch commits, so mid-batch the density's numerator
shrank without the denominator following. Track the in-flight batch's
progress as processingBlockNumber (advanced in advanceAfterBatch, caught
up in applyBatchProgress, rewound on rollback) and use it as the span's
lower boundary.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018CiEziFbVe1P3Y6iuyfT5Z
* Warm the chain with seed events in the partition-merge E2E test
A chain with no density signal now targets frontier + 20k, which gates the
far DC partitions this test fetches in parallel. Seed 100 events in the
registering response so the chain has a density signal and enough range
budget for DC2's full 10-chunk pipeline; cold gating itself is covered by
unit tests.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018CiEziFbVe1P3Y6iuyfT5Z
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Reserve budget at honest itemsEst and tune scheduler defaults (#1403)
* Reserve budget at honest itemsEst instead of headroomed itemsTarget
Queries now carry both itemsTarget (server-side cap, sized with the chunk
headroom multiplier) and itemsEst (raw density estimate). Reservations,
pendingBudget, and water-fill footprints use itemsEst, so headroom no longer
throttles pipeline depth. The extra 3x budget cap for caught-up chains is
dropped — truncation safety lives solely in the itemsTarget cap, keeping
realtime headroom at 3x instead of compounding to 9x. Aligned chains may now
run 5% past the leader's line to stop clamp flapping when progress tracks
closely.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QyDQ2imktXA4jL8PtWYSmd
* Raise default target buffer to 100k and chunk pipeline cap to 12
Measured on the erc20 template against real HyperSync data: at 50k the dense
chain's buffer drained to zero in a quarter of samples (processing starved on
fetching), while at 100k it almost never does and throughput matches the
processing ceiling. Beyond 100k there's no further gain — 300k only grows the
resident buffer. The chunk cap rarely binds at 12 but gives the pipeline
headroom at the larger budget.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QyDQ2imktXA4jL8PtWYSmd
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Fix future end block progress alignment (#1406)
* Keep below-head chains polling instead of dropping them (NothingToQuery)
At realtime (and during backfill), when one chain falls far behind and its
query reservation drains the shared fetch-buffer budget, a chain that is below
its own head gets no query this tick. Being below head it also won't wait for a
new block, so getNextQuery returns NothingToQuery. checkAndFetch never
dispatches NothingToQuery, so that chain stops fetching AND stops polling
getHeightOrThrow — its head tracking freezes. This reproduced two production
stalls: one right before the indexer enters isReady, and one after isReady
having queried only a few items.
Dispatch such a chain as WaitingForNewBlock so it keeps polling, mirroring the
existing knownHeight == 0 guard. A chain is still left idle (undispatched) when
it is genuinely so: caught up to its head/endblock, still draining in-flight
queries, or holding ready items that batch processing will drain and
re-schedule from.
Add an E2E regression test that drives two chains to realtime, then a divergent
height jump (leader far ahead, follower just past its own head), and asserts the
near-head follower keeps polling getHeightOrThrow while the leader backfills.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GBSAcMXTNy2K8i16bkJELo
* Extract client-side address filtering from FetchState (#1414)
* Filter over-fetched events before contract registration
Over-fetched events (a merged partition returning an address before its
effectiveStartBlock, or a wildcard param referencing an address registered
after the log's block) were running their contractRegister handlers and
spawning dynamic contracts before being dropped from the buffer.
Apply the client-side address filter to the contract-register set before
running the handlers. Extract the predicate as FetchState.filterByClientAddress
and expose it through ChainState so ChainFetching can gate registration; the
buffer is still filtered after registration in handleQueryResult, so events
referencing a contract registered in the same batch keep routing to handlers.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
* Move client address filter fully before contract registration
Follow-up to the previous commit: instead of only gating the contract-register
set, apply the client-side address filter to the whole response up front, so an
over-fetched event neither spawns dynamic contracts nor enters the buffer.
This is only correct if a non-wildcard event for an address registered in the
same batch can't appear before its registration — which a real backend
guarantees, since a query only returns logs for the addresses it was sent. The
simulate source didn't model that (it dumped every item on the first call), so
make it faithful: return only items matching the query's block range, selection,
and (for non-wildcard events) address set, delivering each once; wildcards are
over-fetched for the client filter to gate, mirroring HyperSync. A contract
registered mid-run now surfaces its events in the follow-up query the
registration triggers, exactly as in production.
Parse simulate items at the process's startBlock (not the config default) so
they land in the range the source is queried over. The dead-input tracker stays
downstream, observing processed batches, so it still reports items excluded by
any filter.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
* Merge buffer with a single sort-free pass instead of re-sorting
Buffer accumulation re-sorted the whole buffer on every response via
Array.sort(compareBufferItem) — an O(n log n) pass whose comparator crosses the
JS↔native boundary on each comparison — plus a Set of string keys for dedup.
Replace it with mergeIntoBuffer: the buffer is already sorted, so insertion-sort
just the (small, usually ascending) response and merge the two runs in one linear
pass, dropping duplicates as adjacent-equal. Comparison is inlined
(compareBufferItem now returns an int with explicit field compares and a
registration-index tiebreaker) with no Array.sort callback and no allocated key.
updateInternal assumes a sorted buffer (hot paths pass mutItemsSorted=true) and
normalizes arbitrary input otherwise; onBlock items are generated as their own
sorted run and merged in the same way.
~14-20x faster on realistic buffers (see packages/envio/bench). Adds a
mergeIntoBuffer correctness test.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
* Address review: drop bench, single onBlock merge, simplify test helper
- Delete the standalone benchmark script.
- updateInternal now folds onBlock items into the buffer with a single merge at
the end instead of merging mid-function; block items stay their own sorted run
so the merge remains linear.
- makeInitialWithOnBlock returns the fetch state directly (indexing addresses
were unused by every caller).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017xrChwhzSShi39DwN2iKV5
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Replace water-fill budget algorithm with greedy fromBlock-sorted pass (#1415)
* Cap open-ended probe fan-out in the fetch water-fill
When the fresh per-tick budget is thin relative to the number of
partitions, the water-fill split gives each partition a sub-item
allotment that the open-ended emit floors to a 1-item query, so a
single tick fires a burst of near-empty probes and overshoots the
budget.
Concentrate instead: serve only the neediest
ceil(rangeItemsTarget / minQueryItems) probe partitions this tick, each
taking a full ~minQueryItems-sized probe, and let the rest wait until
freed reservations grow the budget. Chunk partitions self-limit via
density-sized chunks and are never capped, so normal fan-out and
post-rollback resume are untouched.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Keqij8JHea79B2rqJX4ApZ
* Select fetch queries by fromBlock against a chain budget
Replace the per-partition water-fill (and the earlier probe-fan-out cap)
with a single budget pass:
1. Generate every candidate query for the tick with no budget check —
gap-fill holes, plus each in-range partition's density-sized chunks or,
for an unknown-density partition, one open-ended probe sized to its even
share of the fresh budget (freshBudget / inRangeCount).
2. Sort all candidates by fromBlock.
3. Accept them in that order while the budget (chainTargetItems minus
in-flight reservations) stays positive; the query that tips it negative
is still accepted, everything after it waits for a later tick.
Selecting by fromBlock spends the budget on the earliest blocks across all
partitions first, so the frontier advances evenly and no partition is
starved by iteration order — and gap-fill, chunks, and probes all stop
together once the budget is spent. Removes waterLevel and the minQueryItems
cap.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Keqij8JHea79B2rqJX4ApZ
* Size open-ended probes by chain density over the range to the target
An open-ended probe now reserves chainDensity × (chainTargetBlock −
fromBlock + 1) / partitionCount — the events its range to the target is
expected to hold, split across partitions — instead of an even share of
the fresh budget. ChainState passes its effectiveDensity down for this.
When the chain has no density signal, or the partition is already at the
target (no range), it falls back to the even budget share so cold chains
and caught-up partitions still probe.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Keqij8JHea79B2rqJX4ApZ
* Size probes by budget-implied density over the in-range coverage
Replace the passed-in chainDensity with a rangeTargetDensity derived
inside getNextQuery: freshBudget / (chainTargetBlock − frontierCursor + 1),
where frontierCursor is the furthest-behind in-range cursor. A probe then
reserves rangeTargetDensity × (chainTargetBlock − fromBlock + 1) /
inRangeCount, so a partition covering less of the range to the target (it
sits further ahead) gets proportionally fewer items, while the furthest-
behind partition gets the full even share.
Measuring the range from the in-range frontier (not the chain buffer
frontier) keeps a lone in-range partition on the full budget instead of
having it diluted by out-of-range laggards, and drops the chainDensity
parameter ChainState was threading down.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Keqij8JHea79B2rqJX4ApZ
* Optimize greedy budget pass: fewer sweeps, bounded generation (#1418)
- Fold the chainReserved sum and partitionIndexById build into the
Phase A partition sweep (3 full passes over partitions -> 1).
- Cap per-partition chunk generation at the fresh budget: a partition
can be accepted at most the budget plus one overshoot, so further
chunks can never be accepted. Shrinks the candidate set and sort cost
when the budget is small relative to the pending-chunk cap.
- Acceptance pass: sort candidates in place and stop at the first
candidate that can't be accepted, instead of copying via toSorted and
scanning the whole tail with forEach.
- Hoist the loop-invariant chunk-start ceiling out of the chunk loop.
- Rename waterFillState -> partitionFillState (no water-fill left).
Claude-Session: https://claude.ai/code/session_01Cj7fN5nh9d2rLeWAXnD1d5
Co-authored-by: Claude <noreply@anthropic.com>
* Fix budget deadlock when gap-fill precedes returned query (#1419)
* Let gap fills bypass the fresh-budget gate
A gap-fill candidate was gated on the fresh forward-progress budget, so a
partition could deadlock after a partial/out-of-order chunk: chunk [101,200]
returns and lingers in mutPendingQueries behind an unfilled [51,100] hole,
its reservation already released by ChainState, yet the FetchState budget
sweep still counted it — driving freshBudget to 0 and dropping the [51,100]
gap-fill every tick, so the returned query could never be consumed.
Fix by budgeting acceptance against the full chainTargetItems and reserving
in-flight queries per-query in fromBlock order: a gap-fill, whose fromBlock
precedes the query it unblocks, claims budget ahead of that reservation.
Returned-but-unconsumed queries (fetchedBlock set) no longer count toward the
budget, matching the release ChainState already performed.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S6hp9FfBBT5insJwt2e28F
* Charge same-block reservations before fresh candidates
On a fromBlock tie, order in-flight reservations ahead of fresh candidates in
the acceptance stream. A same-block candidate could otherwise be emitted while
the pool budget was already exhausted (chainTargetItems still carrying
pendingBudget), pushing total reserved work past the target buffer. Only a
strictly-earlier candidate — a gap-fill preceding the query it unblocks —
should borrow ahead of a reservation.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01S6hp9FfBBT5insJwt2e28F
---------
Co-authored-by: Claude <noreply@anthropic.com>
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Separate event density from source range capacity (#1423)
* Separate and smooth per-partition event density (#1426)
* Separate event density from source range capacity
* Enable strict warning checks in ReScript configurations (#1424)
* Treat ReScript warning 23 as an error in indexer configs
Promote the "useless record with clause" warning to an error in the
generated-project template and the test scenarios. The envio runtime
package already errors on all warnings via "+a".
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DGX7HGV5nCwFHHoazo8dCM
* Enforce all ReScript warnings as errors in test scenarios
Set warnings.error to "+a" for the test_codegen, fuel_test, and svm_test
scenarios, matching the envio runtime package. Leave the user-facing
generated-project template without a warnings override.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DGX7HGV5nCwFHHoazo8dCM
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Smooth per-partition event density
* Fix strict ReScript warnings after main merge
* Trust event density independently from source capacity
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Fix reorg-threshold cross-chain query stall (#1430)
* Add PIN test reproducing the below-head chain silence stall
Reverts the earlier fix and exploratory tests and pins the exact production
stall on the unfixed scheduler: when one chain falls far behind and its query
reservation drains the shared fetch-buffer budget, a chain below its own head
but starved of budget emits no query and (being below head) won't wait for a new
block, so getNextQuery returns NothingToQuery. checkAndFetch never dispatches
NothingToQuery, so that chain stops querying AND stops polling getHeightOrThrow
and goes silent.
The test asserts the correct behavior — the starved below-head follower keeps
polling getHeightOrThrow. It is RED on this unfixed scheduler (the follower never
re-polls) and turns green once below-head chains are dispatched as
WaitingForNewBlock instead of being dropped (the "Keep below-head chains polling"
change). Verified red without the change and green with it.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VhitjdvBNbfY6tRnv6RQcw
* Fix reorg-threshold cross-chain query stall
* Deduplicate fetch progress calculation
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Add minimum query admission budget (#1429)
* Add minimum query admission budget
* Keep block waiters outside query admission
* Keep block waiting in query selection
* Pause all chain actions below admission floor
* Anchor cross-chain alignment to most-behind chain's frontier (#1434)
* Anchor cross-chain alignment line at the most-behind chain's frontier
The waterfall's alignment line was only established on ticks where the
most-behind chain itself emitted a fresh query and had a density signal.
While that chain's queries were in flight (or it was still cold), every
other chain fetched unclamped to its own head, defeating the cross-chain
ordering the line exists for.
- Derive the line from the most-behind known-height chain's fetch-frontier
progress before dispatching, so it holds…
Summary
Introduces per-chain effect caching and rate limiting via a new
crossChainoption (defaults totruefor backward compatibility). Chain-scoped effects (crossChain: false) now have isolated caches and rate-limit budgets per chain, and exposecontext.chain.idto read the chain the handler was invoked on. Cross-chain effects continue to share a single global cache.Key Changes
Effect scope model: Added
Internal.chainScopetype to represent whether data is shared globally (CrossChain) or isolated per chain (Chain(id)). Unboxed for zero-cost runtime representation.Cache table addressing: Centralized all cache table naming logic in
Internal.EffectCachemodule with reversible mappings:envio_effect_<name>→<name>.tsvenvio_<chainId>_effect_<name>→<chainId>/<name>.tsvPer-scope rate limiting: Moved rate-limit state from the effect definition to the in-memory cache table (
IndexerState.effectCacheInMemTable), so each chain gets its own window and queue. Chain-scoped effects now rate-limit independently per chain.Context chain access:
context.chainis now available on chain-scoped effects and throws a descriptive error on cross-chain effects. Implemented via non-enumerable properties on the effect context instance.Nested effect validation: Cross-chain effects cannot call chain-scoped effects (no single chain to resolve against); throws before any cache work.
Cache directory structure:
.envio/cachenow supports subdirectories named by chain id for chain-scoped caches.scanCacheDir()handles both flat files (cross-chain) and nested structure (chain-scoped), rejecting non-numeric directories that contain TSVs.Storage persistence: Updated
Persistence.effectCacheRecordto trackscopeandtableName(the full cache address) alongsideeffectName, keyed bytableNameto keep cross-chain and chain-scoped caches independent.Notable Implementation Details
crossChainoption defaults totrue, preserving existing behavior for all effects unless explicitly set tofalse.InMemoryStore.getEffectInMemTable()to ensure each scope gets its own state.LoadLayer.callEffect()now operates on the in-memory table's rate-limit state instead of the effect definition.https://claude.ai/code/session_01X47KFbCFtGSXgGqFsBrCgH
Summary by CodeRabbit
crossChainconfiguration, withcontext.chain.idavailable for chain-scoped effects and restricted behavior for cross-chain effects.effectandscope.fs.promises.statbindings.crossChainoption semantics and related cache/rate-limit behavior.