Skip to content

fix(logs): harden log schemas against API response format variations#361

Merged
BYK merged 6 commits intomainfrom
fix/cli-bh-harden-log-schemas
Mar 6, 2026
Merged

fix(logs): harden log schemas against API response format variations#361
BYK merged 6 commits intomainfrom
fix/cli-bh-harden-log-schemas

Conversation

@BYK
Copy link
Member

@BYK BYK commented Mar 6, 2026

Fixes CLI-BH

The trace-logs endpoint (/organizations/{org}/trace-logs/) can return numeric fields as strings or omit optional fields, causing Zod validation failures in apiRequestToRegion().

Root Cause

TraceLogSchema used strict z.number() for fields the API may return as strings or omit:

  • timestamp_precise — nanosecond timestamps (~1.7e18) exceed Number.MAX_SAFE_INTEGER, so the API may serialize them as strings
  • project.id — some responses return numeric IDs as strings
  • severity_number — may be absent from certain log entries

Changes

  • Schema hardening (src/types/sentry.ts): Use z.coerce.number() on timestamp_precise (all 3 log schemas), project.id, and severity_number. Make severity_number and timestamp_precise optional on TraceLogSchema.
  • Follow-mode fallbacks (src/commands/log/list.ts): Handle optional timestamp_precise with ?? lastTimestamp / ?? 0 in dedup filtering.
  • Diagnostics (src/lib/api-client.ts): Attach structured Zod validation issues to Sentry context so future schema failures include field-level details.
  • Tests: Unit tests for string coercion and missing optional fields. Property-based tests for schema coercion invariants.

@github-actions
Copy link
Contributor

github-actions bot commented Mar 6, 2026

Semver Impact of This PR

🟢 Patch (bug fixes)

📋 Changelog Preview

This is how your changes will appear in the changelog.
Entries from this PR are highlighted with a left border (blockquote style).


Bug Fixes 🐛

  • (logs) Harden log schemas against API response format variations by BYK in #361

Internal Changes 🔧

  • (delta-upgrade) Lazy chain walk, GHCR retry, parallel I/O, offline cache by BYK in #360

🤖 This preview updates automatically when you update the PR.

@github-actions
Copy link
Contributor

github-actions bot commented Mar 6, 2026

Codecov Results 📊

101 passed | Total: 101 | Pass Rate: 100% | Execution Time: 0ms

📊 Comparison with Base Branch

Metric Change
Total Tests
Passed Tests
Failed Tests
Skipped Tests

✨ No test changes detected

All tests are passing successfully.

✅ Patch coverage is 82.76%. Project has 3656 uncovered lines.
❌ Project coverage is 81.5%. Comparing base (base) to head (head).

Files with missing lines (2)
File Patch % Lines
api-client.ts 62.01% ⚠️ 430 Missing
list.ts 92.51% ⚠️ 25 Missing
Coverage diff
@@            Coverage Diff             @@
##          main       #PR       +/-##
==========================================
- Coverage    81.51%    81.50%    -0.01%
==========================================
  Files          128       128         —
  Lines        19736     19767       +31
  Branches         0         0         —
==========================================
+ Hits         16087     16111       +24
- Misses        3649      3656        +7
- Partials         0         0         —

Generated by Codecov Action

@BYK BYK marked this pull request as ready for review March 6, 2026 10:48
@BYK BYK changed the title fix(CLI-BH): harden log schemas against API response format variations fix(logs): harden log schemas against API response format variations Mar 6, 2026
BYK added 5 commits March 6, 2026 11:43
- Use z.coerce.number() on timestamp_precise in SentryLogSchema,
  DetailedSentryLogSchema, and TraceLogSchema to handle APIs returning
  large nanosecond timestamps as strings (exceeds Number.MAX_SAFE_INTEGER)
- Use z.coerce.number() on TraceLogSchema project.id and severity_number
  for resilience against string-typed numeric fields
- Make TraceLogSchema severity_number and timestamp_precise optional since
  the trace-logs API may omit them
- Update LogLike type and follow-mode dedup logic to handle optional
  timestamp_precise with safe fallbacks
- Attach structured Zod validation issues to Sentry context in
  apiRequestToRegion() for better error diagnostics
- Add unit tests for string coercion and missing optional fields
- Add property-based tests verifying schema coercion invariants
Logs without timestamp_precise were silently dropped in follow mode
because the fallback `?? 0` always evaluates to `0 > lastTs` = false.
Use explicit undefined check to always include such logs instead.
…ow mode

When timestamp_precise is absent, use a Set of seen log IDs to
prevent the same logs from being re-displayed on every poll cycle.
Logs with timestamp_precise still use the fast numeric comparison.
- Add onInitialLogs callback to FollowConfig so trace follow mode
  seeds the seenWithoutTs set from the initial batch, preventing
  duplicates on the first poll cycle.
- Replace Math.random() in property tests with fast-check combinators
  (oneof, constant, tuple) for deterministic reproducibility.
…irst log

When the newest log in a poll batch lacks timestamp_precise, scanning
only newLogs[0] fails to advance lastTimestamp, causing logs with
timestamp_precise to be re-displayed on subsequent polls. Use a
maxTimestamp() helper that finds the highest value across the entire
batch for both initial fetch and poll updates.
@BYK BYK force-pushed the fix/cli-bh-harden-log-schemas branch from 98d364c to 24474d6 Compare March 6, 2026 11:44
The maxTimestamp() helper scans the entire batch, so the poll's
afterTimestamp is the highest value in sampleLogs, not sampleLogs[0].
Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

@BYK BYK merged commit 328d262 into main Mar 6, 2026
20 checks passed
@BYK BYK deleted the fix/cli-bh-harden-log-schemas branch March 6, 2026 12:03
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