Skip to content

refactor(ai_token): Cleaned up error messages - #52

Merged
SteakFisher merged 2 commits into
mainfrom
refactor/ai_token
May 23, 2026
Merged

refactor(ai_token): Cleaned up error messages#52
SteakFisher merged 2 commits into
mainfrom
refactor/ai_token

Conversation

@SteakFisher

@SteakFisher SteakFisher commented May 23, 2026

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • Bug Fixes
    • Streaming now continues processing subsequent events after individual event failures (partial-success).
    • Responses include per-event failure details and clear summary counts of processed vs failed events.
    • Database constraint violations (duplicate keys) are detected and surfaced with clearer, user-facing messages.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 23, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: c6227074-c74c-4ca6-9e10-d5046748857a

📥 Commits

Reviewing files that changed from the base of the PR and between 611cb8a and c5a9e8f.

📒 Files selected for processing (3)
  • proto
  • src/routes/gRPC/events/streamEvents.ts
  • src/storage/adapter/postgres/handlers/addEventUtils.ts

📝 Walkthrough

Walkthrough

Event streaming now collects per-request failures instead of aborting, mapping errors to standardized failure codes and reporting detailed failure entries; the Postgres adapter extracts DB error codes and reclassifies duplicate-key violations as structured storage errors; proto submodule pointer updated.

Changes

Partial-Success Event Streaming with Error Classification

Layer / File(s) Summary
PostgreSQL Error Classification
src/storage/adapter/postgres/handlers/addEventUtils.ts
Adds getPostgresErrorCode() and hasPostgresErrorCode() to extract Postgres code from nested/wrapped errors and updates executeInTransaction to detect 23505 duplicate-key violations and rethrow as StorageError.constraintViolation().
Partial-Success Streaming with Failure Collection
src/routes/gRPC/events/streamEvents.ts
Adds getFailureCode() and publicMessageForCode(), initializes failures and eventIndex, records Sentry breadcrumb/exception on per-request errors, appends EventFailure entries instead of aborting the stream, and builds StreamEventResponse with eventsProcessed, eventsFailed, and failures; updates wideEventBuilder context with failure metadata.
Proto submodule pointer update
proto
Updates the proto git submodule reference to a new commit hash.
sequenceDiagram
  participant Client
  participant StreamHandler as streamEvents
  participant Storage
  participant Sentry
  participant ResponseBuilder
  Client->>StreamHandler: stream event requests
  loop per request
    StreamHandler->>Storage: attempt add/process event
    alt Storage/error
      Storage-->>StreamHandler: throw error
      StreamHandler->>StreamHandler: getFailureCode(error)
      StreamHandler->>Sentry: add breadcrumb + captureException(eventIndex,idempotencyKey,errorCode)
      StreamHandler->>ResponseBuilder: append EventFailure(eventIndex,idempotencyKey,errorCode,message)
    else success
      StreamHandler->>ResponseBuilder: increment eventsProcessed
    end
    StreamHandler->>StreamHandler: eventIndex++
  end
  StreamHandler->>ResponseBuilder: build StreamEventResponse(eventsProcessed, eventsFailed, failures)
  ResponseBuilder->>Client: send final response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • ScrawnDotDev/Scrawn#45: Related to unique idempotency_key constraints that can trigger duplicate-key violations handled here.

Poem

🐰 I hop through streams and patch the flow,
Collecting bumps so callers know—
Each index saved, each error named,
Soft failures logged, the stream remained.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The title 'Cleaned up error messages' is generic and does not accurately reflect the main changes: adding partial-success streaming with error handling, PostgreSQL error code detection, and failure tracking in event processing. Revise the title to better reflect the primary change, such as 'Add partial-success streaming with failure tracking for event processing' or 'Support graceful event streaming with per-request error handling'.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/ai_token

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 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 `@src/routes/gRPC/events/streamEvents.ts`:
- Around line 85-89: The current code assigns raw exception text to
failure.message (in the EventFailure created in streamEvents.ts), which can leak
internal details; instead, map failure.errorCode (from
getFailureCode(innerError)) to a stable public message (e.g., via a helper like
publicMessageForCode(errorCode) with a default "internal server error"), set
failure.message to that stable string, and send the full innerError to Sentry
(captureException) along with context (idempotencyKey, eventIndex, errorCode) so
internal details are recorded but not returned to clients.
- Around line 17-31: getFailureCode currently detects Zod errors by matching
err.name and may propagate raw Zod messages; update it to explicitly import and
check against ZodError (use `err instanceof ZodError`) or ensure callers
normalize ZodError into a domain ValidationError before calling getFailureCode,
and change the code path that maps Zod innerError.message into the failure
payload to instead set a safe, generic validation message (e.g.,
"VALIDATION_FAILED" with a sanitized message) while sending full Zod details to
Sentry/logging; modify getFailureCode and any callers (e.g., streamEvents
handlers) to use the explicit ZodError check and to avoid copying
innerError.message directly into failure.message.

In `@src/storage/adapter/postgres/handlers/addEventUtils.ts`:
- Around line 41-49: The catch currently maps all errors (except SQLSTATE 23505)
to StorageError.transactionFailed, which overrides existing StorageError types;
update the catch in addEventUtils (the block using hasPostgresErrorCode(e,
"23505") and throwing StorageError.transactionFailed) to first detect and
rethrow existing StorageError instances (e.g., via e instanceof StorageError or
a helper isStorageError) so original StorageError.type (like
invalidTimestamp/invalidData) is preserved; only convert non-StorageError
exceptions (and handle 23505 -> StorageError.constraintViolation) into
transactionFailed as before, keeping operationName in the transactionFailed
message.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 7b86c694-1682-41cb-a059-49dfb5341862

📥 Commits

Reviewing files that changed from the base of the PR and between 128711f and 611cb8a.

⛔ Files ignored due to path filters (1)
  • src/gen/event/v1/event.ts is excluded by !**/gen/**
📒 Files selected for processing (2)
  • src/routes/gRPC/events/streamEvents.ts
  • src/storage/adapter/postgres/handlers/addEventUtils.ts

Comment thread src/routes/gRPC/events/streamEvents.ts
Comment thread src/routes/gRPC/events/streamEvents.ts Outdated
Comment thread src/storage/adapter/postgres/handlers/addEventUtils.ts
@SteakFisher
SteakFisher merged commit 42ac224 into main May 23, 2026
3 checks passed
@SteakFisher
SteakFisher deleted the refactor/ai_token branch May 23, 2026 11:50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant