Skip to content

fix(backend): one top-up writer, honest status codes, one envelope - #1932

Merged
K1NGD4VID merged 4 commits into
LabsCrypt:mainfrom
eazeeshow:kayson/topup-single-writer-and-unified-error-envelope
Nov 21, 2026
Merged

K1NGD4VID merged 4 commits into
LabsCrypt:mainfrom
eazeeshow:kayson/topup-single-writer-and-unified-error-envelope

Conversation

@eazeeshow

Copy link
Copy Markdown
Contributor

Description

Three backend correctness issues that share one root cause — the error path and the top-up write path each had more than one version of the truth — solved together because they collide in the same files.

  1. [Backend] Fix top-up double-write race between API handler and event indexer #1848 — depositedAmount had two independent writers. topUpStreamHandler ran a raw-SQL increment after the chain call, and handleStreamToppedUp wrote the absolute on-chain value from the event. The handler wrote no TOPPED_UP event row, so the transactionHash_eventType dedup key protected neither write. If the indexer committed first, the handler added the amount on top and the stream was permanently overcounted.
  2. [Backend] Return accurate error codes from topUpStreamHandler instead of blanket 400s #1850 — topUpStreamHandler wrapped the chain call, the findUnique and the SQL increment in a single catch that always answered 400 TOP_UP_FAILED. A Postgres outage was reported to the client as "your transaction failed on chain", which invites a retry that pays twice.
  3. [Backend] Unify the duplicated ApiError classes and conflicting error envelopes #1851 — the backend shipped two ApiError classes with swapped constructor signatures, five response shapes, and an RFC 7807 middleware nothing imported.

After this PR there is one ApiError, one sendApiError, exactly one json({ error … }) literal left in backend/src, and exactly one place that decides whether a top-up has already been applied.

Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📚 Documentation update
  • 🔧 Refactoring (no functional changes)
  • 🧪 Test addition or update

Related Issues

Closes #1848
Closes #1850
Closes #1851

Changes Made

#1848 — one writer decides, in either arrival order

backend/src/services/top-up-writer.ts (new) holds both writers, and both take SELECT … FOR UPDATE on the Stream row (top-up-projection.ts:37) and key their bookkeeping on the same StreamEvent (transactionHash, "TOPPED_UP") row:

  • applyTopUpOnce (handler) — applies the increment only when no marker exists, then writes a marker carrying ledgerSequence: 0, which means "applied by a process that has no ledger position". It returns the authoritative depositedAmount either way, which is what the HTTP response now reports.
  • applyToppedUpEvent (indexer) — treats ledgerSequence !== 0 as "I already read this off the chain" and skips, so a replay cannot roll the row back to a stale absolute value. A 0 marker is not skipped: that event is the API's guess meeting its first confirmation, so the indexer overwrites the amount with the absolute new_deposited_amount and rewrites the marker with the real ledger sequence.

handleStreamToppedUp in soroban-event-worker.ts is now a call into that function; the increment/decrement logic it used to own is gone.

endTime also stops being derived twice: projectedEndTime() is the one formula (startTime + deposited/rate + totalPausedDuration, null at rate 0), used by both writers.

Trade-off — why not the issue's preferred Option A. Option A makes the indexer the only writer and reduces the handler to reporting txHash. But TopUpResponse.depositedAmount is a required field in the published contract (backend/swagger/flowfi.openapi.json, mirrored into frontend/src/lib/api-types.generated.ts:3738) and its description promises "New total deposited amount after the top-up" — a promise only a writer can keep. Option A therefore means either a spec change plus regenerated types plus a frontend release, or a required field that silently means "whatever the indexer last saw". This repo gates on exactly that drift, so I kept the contract and took the option the issue lists as acceptable: make the handler's write conditional, inside one transaction, keyed on the event the dedup index already covers. The cost is one new convention — ledgerSequence = 0 now means "chain-unconfirmed", and any future reader of StreamEvent has to know it. It is documented at the constant (top-up-writer.ts:9-14), and applyTopUpOnce returns the row's authoritative amount whether or not this call applied it, so the response stays truthful.

Existing damage. backend/docs/TOP_UP_DEPOSITED_AMOUNT_REPAIR.md is the runbook: why the event log alone can prove or repair the drift (the handler wrote no event, so absent rows are indeterminate — chain is the only witness), a read-only audit query, the repair statement with its dry-run guard, a verification pass, and escalation for negative drift. No migration is included: repairing production rows from a PR is not something to do by hand at merge time.

#1850 — status codes that mean what they say

topUpStreamHandler now has three exits instead of one:

condition before after
contract call reverts or simulation fails 400 TOP_UP_FAILED 400 TOP_UP_FAILED (unchanged, narrowed to the chain call only)
stream disappears between the pre-flight read and the lock 400 TOP_UP_FAILED 404 NOT_FOUND, same code as the pre-flight read so a caller cannot tell which lookup missed
Prisma error (P2002/P2025/P2003/…) 400 TOP_UP_FAILED fromPrismaError mapping (409 DUPLICATE_ENTRY, 404 RESOURCE_NOT_FOUND, …)
any other DB/unknown failure 400 TOP_UP_FAILED 500 INTERNAL_SERVER_ERROR

depositedAmount: updatedStream!.depositedAmount is gone — the value now comes back from the writer, so there is no non-null assertion in the handler (grep '[A-Za-z_)\]]!\.' backend/src/controllers/stream.controller.ts returns nothing) and no second read that can miss.

#1851 — one envelope

lib/api-error.ts is the only implementation; types/api-error.ts is deleted. Both use (statusCode, code, message, details?) — the order sendApiError already had, because code is what clients branch on and message is display text. sendApiError omits details entirely when it is undefined rather than sending details: null.

The five ad-hoc shapes are replaced at their sites, e.g.:

site before after
middleware/auth.ts { error: 'Unauthorized', message } 401 {error:{code:'UNAUTHORIZED',message}}
controllers/stream/simulate.ts flat { error, code } envelope, keeping that file's own lowercase codes
controllers/stream.controller.ts:135 { error, message } 409 {error:{code:'STREAM_NOT_CONFIRMED',message,details:{hint}}}
controllers/webhook.controller.ts:40 { error: error.message } 400/500 envelope with a stable code
middleware/error.middleware.ts { message: 'Internal server error' } 500 {error:{code:'INTERNAL_SERVER_ERROR',…}}
src/app.ts CORS rejection { error: err.message } 403 {error:{code:'FORBIDDEN',message}}
middleware/schema-validator.middleware.ts RFC 7807 application/problem+json deleted

error.middleware.ts no longer reaches through (err as any) to find an ApiError: it narrows with instanceof ApiError, and a status-only duck-shaped error is handled by one explicit statusOf() helper with a comment saying why it exists (the body-parser and cors packages throw their own errors we do not own).

schema-validator.middleware.ts: deleted, not wired up. It was never imported, never in a route, and its contract contradicted both the shipped OpenAPI Error schema and every test in the repo. Wiring it up would have meant migrating ~184 call sites to a second envelope; the issue asks for one envelope, so RFC 7807 is the thing that goes. Nothing in backend/, frontend/ or docs/ references it any more (grep -rn 'schema-validator\|7807\|problem+json' is empty outside ignored backend/dist).

Repairs needed to make the suite green (not part of any issue)

tests/integration/cancel-status-filter.test.ts and tests/integration/stream-lifecycle.test.ts each ran an unscoped deleteMany() over Stream/StreamEvent/User in beforeEach. Vitest runs test files in parallel forks against one database, so whichever file seeded second had its fixtures deleted mid-test. Both cleanups are now scoped to the rows their own file seeds (explicit streamId list plus the per-process Keypair.random() wallets). See Baseline below — this is a pre-existing failure on main, reproduced on an untouched checkout.

Documentation

The prose advertised the shapes this PR removes. backend/README.md now states the envelope once (including 429 RATE_LIMITED, 413 PAYLOAD_TOO_LARGE and the CORS 403 FORBIDDEN), and AUTHENTICATION.md, SANDBOX_MODE.md, API_VERSIONING.md and DEPRECATION_POLICY.md show the codes the middleware really returns. The 410 Gone sunset body in the deprecation docs is marked not yet implemented rather than silently reshaped, because no route in src/ produces it.

Testing

Baseline (proves which failures are pre-existing)

Run against an untouched git archive export of origin/main at 2a1a259, same Postgres, same commands:

$ cd backend && npm run build
BUILD_RC=0
$ DATABASE_URL=… NODE_ENV=test npx vitest run --coverage --reporter=basic
   × API cancel → cancelled status filter (issue #1219) > writes a provisional CANCELLED event so the stream appears under status=cancelled
     → expected 404 to be 200 // Object.is equality
 Test Files  1 failed | 84 passed (85)
      Tests  1 failed | 1067 passed | 6 skipped (1074)
TEST_RC=1

That failure is the parallel-fork fixture race described above; it is red on main today and this PR is what makes it green.

This branch

$ cd backend && npm run build                                   # tsc over src/ AND tests/
BUILD_RC=0

$ cd backend && npm run codegen:openapi                         # drift gate
OPENAPI_RC=0
$ cd frontend && npm run codegen:api-types
APITYPES_RC=0
$ git diff --exit-code -- backend/swagger/flowfi.openapi.json frontend/src/lib/api-types.generated.ts
DRIFT_RC=0                    # no regeneration: components.schemas.Error already documents {code,message,details}

$ cd backend && NODE_ENV=test npx vitest run --coverage --reporter=basic
 Test Files  85 passed (85)
      Tests  1071 passed | 6 skipped (1077)
All files          |   79.36 |    82.54 |   77.92 |   79.36
TEST_RC=0                      # thresholds are 60/60/60/60

$ cd frontend && npm run lint && npm run test:coverage && npm run build && scripts/check-bundle-size.sh
 Test Files  101 passed (101)
      Tests  1108 passed | 1 skipped (1109)
✓ Compiled successfully in 19.9s
Frontend JS bundle gzipped size: 564494 bytes (614400 byte budget)   BUNDLE_RC=0

# docs-encoding job (each *.md decoded, mojibake classes rejected)
DOCS_RC=0

Test Steps

  1. cd backend && npm run build
  2. DATABASE_URL=postgresql://postgres:password@127.0.0.1:5432/flowfi_test NODE_ENV=test npx vitest run --coverage tests/integration/top-up.test.ts — covers both arrival orders and two concurrent writers on one stream.
  3. Same command with tests/soroban-event-worker.test.ts — the marker-with-0 reconcile path and the skip path.
  4. Same command with tests/integration/cancel-status-filter.test.ts tests/integration/stream-lifecycle.test.ts run together; on main that pair is red, here it is green.

Test Coverage

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing performed

Breaking Changes

Breaking Changes:

  • Every 4xx/5xx JSON body changed shape. Anything that read body.error as a string — or read body.message / body.code at the top level — must now read body.error.message and branch on body.error.code. This includes 429 from the rate limiter, 413 from the body-size limiter, and the CORS 403, which previously bypassed the funnel entirely.
  • 400 TOP_UP_FAILED is no longer returned for server-side failures on POST /v1/streams/:id/top-up; those are 500 INTERNAL_SERVER_ERROR ([Backend] Return accurate error codes from topUpStreamHandler instead of blanket 400s #1850). Monitors keyed on 400 for DB incidents will now see 5xx, which is the point of the issue.
  • backend/src/types/api-error.ts is deleted. It was exported to nothing outside src/ (the build proves it), but anything importing it from a script breaks.
  • StreamEvent.ledgerSequence = 0 becomes meaningful: it marks a row written by the API, not by the indexer. Dashboards or queries that treat 0 as "unknown ledger" will now see it as a real state.

Migration Guide:

- const message = body?.error ?? 'request failed';
+ const message = body?.error?.message ?? 'request failed';
+ if (body?.error?.code === 'RATE_LIMITED') { /* back off */ }

The only frontend reader of the old flat shape was fetch in frontend/src/lib/api/webhooks.ts, updated here along with its test. Consumers should read code and treat message as display text — it is the part that is allowed to change.

Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas (why 0 means unconfirmed; why the marker is reconciled rather than skipped; why Option B over the issue's Option A)
  • I have made corresponding changes to the documentation
  • Updated Postman/Hoppscotch API collections if routes changed — checked: no routes or verbs changed, and docs/api/flowfi.postman_collection.json already documents the envelope verbatim, so no edit was needed
  • If routes or response shapes changed, ran the OpenAPI api-types drift check (npm run codegen:openapi in backend/, then npm run codegen:api-types in frontend/) and committed the regenerated flowfi.openapi.json / api-types.generated.ts — both ran; both files are byte-identical, because components.schemas.Error in the spec already described {code,message,details}. The spec was aspirational and the code is what moved.
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published
  • I have checked for breaking changes and documented them if applicable
  • If this change adds or modifies a metric, I have updated the Grafana dashboard and the alert rules in backend/docs/observability/ — no metric added or renamed; the only new log lines are logger.info

Additional Notes

Conflict with #1930 (Ajoke's wave-14 batch), same base 2a1a259, and GitHub reports both mergeable only because neither has merged yet. #1930 adds requestId to backend/src/types/api-error.ts — the file this PR deletes — and moves requestIdMiddleware ahead of globalRateLimiter in backend/src/app.ts. Whichever lands second needs a small port:

// backend/src/lib/api-error.ts, inside sendApiError
const requestId = res.getHeader('X-Request-ID');
if (typeof requestId === 'string') error.requestId = requestId;

plus requestId?: string on ApiErrorBody there instead of in types/api-error.ts, and #1930's soroban-event-worker.ts change re-applied inside top-up-writer.ts rather than at the old call site. Suggested merge order: this PR first (it deletes a file #1930 edits), then #1930 rebases with the four lines above. Say the word and I will do that port on #1930's branch instead.

Found and deliberately not changed:

  • handleFeeCollected (soroban-event-worker.ts:1242) does its dedup read and its streamEvent.upsert as two separate top-level prisma calls, i.e. exactly the class of race [Backend] Fix top-up double-write race between API handler and event indexer #1848 describes for top-ups. fix(backend): fee-event atomicity, request-id propagation, and the #1764/#1766 coverage gaps #1930 already wraps that pair in $transaction, so this PR leaves it alone rather than colliding with it.
  • [Backend] Unify the duplicated ApiError classes and conflicting error envelopes #1851 unified the envelope shape, not every code string. src/ now emits 54 distinct codes, six of which are lowercase: invalid_params, simulation_error, invalid_token_address, token_list_failed, token_lookup_failed, undecodable_payload. They predate this PR, they are pinned by teammate tests, and renaming them is a second breaking change clients would rather get separately. Happy to file it.
  • VALIDATION_ERROR.details has two shapes for the same code. Four sites (stream.controller.ts:687, stream/simulate.ts:73, sse.controller.ts:128, compliance.routes.ts:117) pass raw zod issues, so path is a string array; error.middleware.ts:62 maps them and joins path into a dotted string. The README and the Postman collection document the zod-native array form because it is the majority. Normalising it means touching assertions in suites this PR does not own.
  • webhook.controller.ts returns 500 INTERNAL_SERVER_ERROR with error.message || "Failed to create webhook" — an unfiltered exception string on a 500, unlike error.middleware.ts which sanitises database detail through fromPrismaError. Pre-existing ({ error: error.message } on main at the same line); this PR changed the shape around it, not the text, so it is a live disclosure worth its own issue.

Four commits, so the code change, the test migration and the prose can be read apart: 6ca5339 (fix + tests + the #1848 runbook), 5ae876b (test-only: upstream's new sse-auth-cleanup.test.ts pinned six assertions to the flat bodies #1851 replaces), 745c15e + a135653 (docs). 60 files, +1416/−820.

LabsCrypt#1848 - depositedAmount had two writers applying the same top-up: the API
handler incremented and the Soroban indexer wrote the absolute on-chain
value, with nothing joining them. Both now run inside one transaction, take
the stream's row lock, and key on the same (transactionHash, TOPPED_UP)
marker, so whichever commits second leaves the amount alone. The API's marker
records ledgerSequence 0, which the indexer treats as "never confirmed" and
reconciles against the event instead of skipping, so chain state stays
authoritative in both arrival orders. endTime is projected by one shared
helper on both paths, and backend/docs/TOP_UP_DEPOSITED_AMOUNT_REPAIR.md
documents how to audit and repair the rows the old race already drifted.

LabsCrypt#1850 - topUpStreamHandler wrapped the chain call, the row lock and the
bookkeeping in one catch that answered 400 TOP_UP_FAILED for all of them.
Chain failures keep the 4xx; database and unexpected failures now surface as
their own status (Prisma-mapped or 500 INTERNAL_SERVER_ERROR), and the
`updatedStream!` assertion is gone because the writer returns the amount.

LabsCrypt#1851 - two ApiError classes with swapped constructor arguments plus five
response shapes meant a caller could silently swap code and message. One
ApiError(statusCode, code, message, details?) and one {error:{code,message,
details?}} envelope remain; the unused RFC 7807 schema-validator middleware
and its tests are deleted. BREAKING for API consumers: every 4xx/5xx body,
including 429 rate limits and the CORS rejection, now uses that envelope.

Also: stream-lifecycle and cancel-status-filter wiped the whole Stream table
in their fixtures. Both files run in parallel against one database, so each
deleted the other's rows mid-assertion; their cleanup is now scoped to the
streams they own.
LabsCrypt#1747's new subscribe tests asserted the flat `{ message }` and
`{ message, errors }` bodies that LabsCrypt#1851 replaces with
`{ error: { code, message, details } }`. Statuses, messages, the Retry-After
header and the "no SSE headers committed" checks are unchanged.
LabsCrypt#1851 leaves exactly one envelope, so the prose has to stop advertising the
shapes it replaced. AUTHENTICATION, SANDBOX_MODE, API_VERSIONING,
DEPRECATION_POLICY and the backend README now show `{error:{code,message,details}}`
with the codes the middleware really sends, and the sunset example is marked
unimplemented instead of implying a 410 no route produces.
@K1NGD4VID
K1NGD4VID marked this pull request as ready for review November 21, 2026 16:15
@K1NGD4VID
K1NGD4VID merged commit e4f4b5c into LabsCrypt:main Nov 21, 2026
16 checks passed
MFrancis-dev added a commit to MFrancis-dev/flowfi that referenced this pull request Nov 21, 2026
…ypt#1932

The API writer and the indexer share one dedup key, and the marker row the
API leaves behind (ledgerSequence 0) is the only case where the indexer
writes through a skip. Nothing pinned which of the two branches a given
existing row takes.
K1NGD4VID pushed a commit that referenced this pull request Nov 21, 2026
#1932 renamed ApiError.status to statusCode and typed details as unknown,
which left the #1935 simulation spec failing the build gate for every backend
branch. Assertions are unchanged: same status, same detail keys.
K1NGD4VID pushed a commit that referenced this pull request Nov 21, 2026
#1932 moved the top-up writes behind applyToppedUpEvent, which takes the
stream row lock through $executeRaw and selects only the columns it needs,
and started storing the event timestamp as a BigInt. The fake client has to
mirror that seam or the suite describes a shape the worker no longer has.
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