Repository navigation
fix(backend): fee-event atomicity, request-id propagation, and the #1764/#1766 coverage gaps - #1930
Merged
K1NGD4VID merged 7 commits intoNov 21, 2026
Conversation
…tion FeeCollected was the only handler that read StreamEvent and then wrote it as two top-level prisma calls, so two deliveries of the same txHash could both pass the dedup check and the second insert hit the unique index. The pair now runs inside prisma.$transaction like every sibling handler, and the atomicity suite proves exactly one committed row for two simultaneous same-hash deliveries plus the rollback path. Closes LabsCrypt#1239
Two gaps, both covered by tests against the real app composition: - sendApiError put an error on the wire with no correlation id, so a caller quoting the body had nothing matching the header. It now mirrors the X-Request-ID the response already carries, read back from the header so a route that overrode it cannot report a different id, and guarded because the stand-in responses in the unit suites have no getHeader. - requestIdMiddleware ran after the global rate limiter, so a throttled 429 and an oversized body from the parser were answered before any id existed. The middleware now sits first, which is what makes the header claim "every response" true rather than "every response the routers saw". Closes LabsCrypt#1494
The worker suite drove one happy event and the admin metrics suite summed whatever the database returned; neither pinned the step where a fee event stops being XDR and becomes the amount and token the per-token totals group on. The new suite builds real ScVals with nativeToScVal and covers the i128/u64 boundaries, both address forms, the documented missing-field failure with what it must not do (no transaction, no row, no broadcast), and dependency failures raising instead of reporting a processed fee. Closes LabsCrypt#1764
Static half asserts the migration converts every Stream timestamp and StreamEvent.timestamp to BIGINT, adds endTime as a nullable column behind the IF NOT EXISTS guard that makes re-running it safe, never routes a timestamp through a floating-point type, and matches schema.prisma. The live half probes information_schema types, round-trips 2^53+1 and the int64 extremes, stores a huge timestamp next to a NULL, and proves a failed $transaction leaves nothing behind. Writes go to a separate schema inside a rolled-back transaction: applying the statements straight to "Stream" would take ACCESS EXCLUSIVE and rewrite it, which stalls the other integration suites that share this database. Closes LabsCrypt#1766
Raheemah2k26
force-pushed
the
fix/wave14-1239-1494-1764-1766
branch
from
November 21, 2026 15:43
0072ac3 to
8715fe4
Compare
21 tasks done
LabsCrypt#1494 made sendApiError stamp requestId onto every error body, but the hand-authored Error schema in the OpenAPI spec still described only code/message/details, so the committed spec and the generated client types contradicted the response the API actually returns. Regenerated backend/swagger/flowfi.openapi.json via codegen:openapi and frontend/src/lib/api-types.generated.ts via codegen:api-types so the drift check stays clean.
…viour The two prose surfaces that describe these paths still narrated the old code: the error envelope was documented without the requestId LabsCrypt#1494 added, and the StreamEvent write path was described as a bare upsert (and, in docs/ARCHITECTURE.md, as a createMany ... skipDuplicates path that the worker has never used). - docs-site api-reference, Postman 400 example, backend/README, docs/ARCHITECTURE, backend/docs/SSE_ARCHITECTURE: error body is { code, message, details?, requestId? } (no `success` field, which the API never emitted), requestIdMiddleware is mounted ahead of the global limiter, and every handler's duplicate check + upsert is one prisma.$transaction. - Verified all eight tx.streamEvent.findUnique call sites sit inside a $transaction, and that no handler emits `success`. Regenerated backend/swagger/flowfi.openapi.json and frontend/src/lib/api-types.generated.ts so the drift check stays clean.
Resolve the api-error move: main relocated the module to src/lib/api-error.ts and rewrote it around the top-up PR's ApiError, so the LabsCrypt#1494 requestId echo now lives there and the old types/api-error.ts is gone. That merge left main red: the LabsCrypt#1935 simulation-errors suite still asserted the pre-move ApiError (status, details: Record<string, unknown>) against a class that now exposes statusCode and unknown details. Narrowed those assertions through one typed helper, and updated the exact-body error assertions in cors and admin-metrics to expect the requestId that LabsCrypt#1494 now adds.
mallison031
pushed a commit
to mallison031/flowfi
that referenced
this pull request
Nov 21, 2026
LabsCrypt#1930 put `requestId` into every `sendApiError` body, so three cursor assertions that pinned the two-field envelope went red. Assert the header value instead of dropping the field: the envelope is still compared in full.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Four independent
Stellar Waveissues for the backend, bundled into one PR:handleFeeCollectedwas the only event handler that checked for aduplicate
StreamEventand then wrote it as two top-levelprismacalls. Twodeliveries of the same
txHash(RPC retry, replay, overlapping poll cycles)could both pass the check, and the second insert tripped the
UNIQUE(transactionHash, eventType)index. It now runs insideprisma.$transaction, matching every sibling handler in the file.not exist yet for responses generated before the routers run.
decode step and the bigint timestamp migration.
Type of Change
Related Issues
Closes #1239
Closes #1494
Closes #1764
Closes #1766
Changes Made
src/workers/soroban-event-worker.ts(#1239) — the dedup read and theupsert moved into one
prisma.$transaction. ThesseService.broadcastToAdmincall stays outside it: the SSE frame is a notification, not part of the atomic
unit, and broadcasting inside would replay it on a retry that ends in a
duplicate.
src/types/api-error.ts(#1494) —ApiErrorBodygainedrequestId, andsendApiErrorfills it from the response's ownX-Request-ID. It reads theheader rather than a second source so a route that overrode the id cannot report
a body value that contradicts its own header, and the read is guarded because
the stand-in responses in the existing unit suites have no
getHeader— anerror handler must not be the thing that throws.
src/app.ts(#1494) —requestIdMiddlewaremoved ahead ofglobalRateLimiter. Without this the header claim "every response" is only truefor responses the routers saw: a throttled 429, and now an oversized body
rejected by the parser, were answered before any id existed.
Scope deliberately stopped there. Many handlers and middlewares write
non-envelope bodies (
{ error: 'Unauthorized' },{ error: 'Invalid publicKey' },the CORS 403) and teammate tests assert those exact shapes; converting them to
the standard envelope is a separate, larger change and would break those suites.
Tests (5 new files, 63 cases)
tests/fee-collected-tx-atomicity.test.ts— a serializing fake$transactionthat buffers writes until commit, proving one committed row fortwo simultaneous same-hash deliveries, one
$transactioncall with notop-level
streamEventread/write, sequential duplicate → one row, and athrowing upsert → nothing committed.
tests/request-id-propagation.test.ts— AC1 header on a 200, an unrouted 404,a throttled 429, and a supplied id kept verbatim vs. an unsafe one replaced;
AC2
error.requestId === X-Request-IDforApiError,ZodError, an unknownErrorand a 413; AC3 log lines stamped without any handler passing the id.AC1/AC2 also run a 150 KB POST through the real
src/app.tschain, becausethe middleware order is the part under test.
tests/request-id-logging.test.ts— the id reaches every level and neverleaks between concurrent requests.
tests/fee-collected-decoding.test.ts— real XDR vianativeToScVal: i128extremes, the hi/lo composition around 2^64, values past
Number.MAX_SAFE_INTEGER, u64 max, both address forms, the documentedmissing body fieldsfailure (and that it writes nothing and broadcastsnothing), and dependency failures surfacing instead of reporting a processed
fee. Also pins the exact
amount/metadata.tokenvalues the adminper-token fee sum groups on.
tests/integration/bigint-timestamp-migration.test.ts— static half assertsthe migration converts every timestamp column to
BIGINT, addsendTimebehind the
IF NOT EXISTSguard that makes re-running it safe, never routes atimestamp through a floating-point type, and agrees with
schema.prisma. Livehalf probes
information_schema, round-trips 2^53+1 and the int64 extremes,stores a huge timestamp next to a
NULL, and shows a failed$transactionleaves nothing behind. Live writes go to a throwaway schema inside a
rolled-back transaction — applying the statements straight to
"Stream"takesACCESS EXCLUSIVEand rewrites the table, which stalls the other integrationsuites sharing this database.
Testing
Local CI replica, Node 22:
Coverage thresholds unchanged, no test skipped or filtered. Baseline proved
first on an untouched
71c242b: 81 files, 972 passed, 6 skipped, and the newsuites dropped into that same tree behave as expected —
fee-collected-tx-atomicity,fee-collected-decodingandrequest-id-propagationfail there (10 cases: no$transactionaround thededup pair, no
requestIdin the envelope, 429 and 413 answered before the idexists), while
request-id-loggingandbigint-timestamp-migrationpass, whichis the point of #1764/#1766: they pin behaviour that is already correct so it
cannot regress silently.
Test Steps
cd backend && npx prisma generate --schema=prisma/schema.prismaDATABASE_URL=postgresql://postgres:password@127.0.0.1:5432/flowfi_test NODE_ENV=test npx vitest run tests/fee-collected-tx-atomicity.test.ts tests/request-id-propagation.test.ts tests/request-id-logging.test.ts tests/fee-collected-decoding.test.tsnpx vitest run tests/integration/bigint-timestamp-migration.test.ts(skips with an explanation whenDATABASE_URLis absent)Notes for the reviewer
tests/integration/cancel-status-filter.test.tsandtests/integration/stream-lifecycle.test.tsare not parallel-safe with eachother on a shared database: each calls a
deleteMany()over the wholeStream/StreamEvent/Userset inbeforeEach, so whichever one seeds firstgets its rows deleted mid-test by the other. Reproduced on an untouched
71c242bby running just those two files together (2 failures); each passes onits own. It is not caused by this PR and I have not touched either file, but a
full-suite run with enough workers will hit it, and the deterministic fix is to
scope each suite's cleanup to its own rows.