Skip to content

fix(backend): fee-event atomicity, request-id propagation, and the #1764/#1766 coverage gaps - #1930

Merged
K1NGD4VID merged 7 commits into
LabsCrypt:mainfrom
Raheemah2k26:fix/wave14-1239-1494-1764-1766
Nov 21, 2026
Merged

K1NGD4VID merged 7 commits into
LabsCrypt:mainfrom
Raheemah2k26:fix/wave14-1239-1494-1764-1766

Conversation

@Raheemah2k26

Copy link
Copy Markdown
Contributor

Description

Four independent Stellar Wave issues for the backend, bundled into one PR:

Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • 🧪 Test addition or update

Related Issues

Closes #1239
Closes #1494
Closes #1764
Closes #1766

Changes Made

src/workers/soroban-event-worker.ts (#1239) — the dedup read and the
upsert moved into one prisma.$transaction. The sseService.broadcastToAdmin
call 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) — ApiErrorBody gained requestId, and
sendApiError fills it from the response's own X-Request-ID. It reads the
header 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 — an
error handler must not be the thing that throws.

src/app.ts (#1494) — requestIdMiddleware moved ahead of
globalRateLimiter. Without this the header claim "every response" is only true
for 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
    $transaction that buffers writes until commit, proving one committed row for
    two simultaneous same-hash deliveries, one $transaction call with no
    top-level streamEvent read/write, sequential duplicate → one row, and a
    throwing 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-ID for ApiError, ZodError, an unknown
    Error and 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.ts chain, because
    the middleware order is the part under test.
  • tests/request-id-logging.test.ts — the id reaches every level and never
    leaks between concurrent requests.
  • tests/fee-collected-decoding.test.ts — real XDR via nativeToScVal: i128
    extremes, the hi/lo composition around 2^64, values past
    Number.MAX_SAFE_INTEGER, u64 max, both address forms, the documented
    missing body fields failure (and that it writes nothing and broadcasts
    nothing), and dependency failures surfacing instead of reporting a processed
    fee. Also pins the exact amount / metadata.token values the admin
    per-token fee sum groups on.
  • tests/integration/bigint-timestamp-migration.test.ts — static half asserts
    the migration converts every timestamp column to BIGINT, adds endTime
    behind the IF NOT EXISTS guard that makes re-running it safe, never routes a
    timestamp through a floating-point type, and agrees with schema.prisma. Live
    half probes information_schema, round-trips 2^53+1 and the int64 extremes,
    stores a huge timestamp next to a NULL, and shows a failed $transaction
    leaves nothing behind. Live writes go to a throwaway schema inside a
    rolled-back transaction — applying the statements straight to "Stream" takes
    ACCESS EXCLUSIVE and rewrites the table, which stalls the other integration
    suites sharing this database.

Testing

Local CI replica, Node 22:

backend $ npm run build                                   # clean
backend $ DATABASE_URL=... npx vitest run --coverage       # 86 files, 1035 passed, 6 skipped
backend $ npm run codegen:openapi
frontend $ npm run codegen:api-types
$ git diff --exit-code -- backend/swagger/flowfi.openapi.json frontend/src/lib/api-types.generated.ts   # clean

Coverage thresholds unchanged, no test skipped or filtered. Baseline proved
first on an untouched 71c242b: 81 files, 972 passed, 6 skipped, and the new
suites dropped into that same tree behave as expected —
fee-collected-tx-atomicity, fee-collected-decoding and
request-id-propagation fail there (10 cases: no $transaction around the
dedup pair, no requestId in the envelope, 429 and 413 answered before the id
exists), while request-id-logging and bigint-timestamp-migration pass, which
is the point of #1764/#1766: they pin behaviour that is already correct so it
cannot regress silently.

Test Steps

  1. cd backend && npx prisma generate --schema=prisma/schema.prisma
  2. DATABASE_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.ts
  3. npx vitest run tests/integration/bigint-timestamp-migration.test.ts (skips with an explanation when DATABASE_URL is absent)

Notes for the reviewer

tests/integration/cancel-status-filter.test.ts and
tests/integration/stream-lifecycle.test.ts are not parallel-safe with each
other on a shared database: each calls a deleteMany() over the whole
Stream/StreamEvent/User set in beforeEach, so whichever one seeds first
gets its rows deleted mid-test by the other. Reproduced on an untouched
71c242b by running just those two files together (2 failures); each passes on
its 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.

…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
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.
@K1NGD4VID
K1NGD4VID merged commit 5b93cc9 into LabsCrypt:main Nov 21, 2026
18 checks passed
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants