Skip to content

test: finops formatting — formatBytes and truncateQuery edge cases#390

Closed
anandgupta42 wants to merge 3 commits intomainfrom
claude/test-finops-formatting-01AfyN3rkDU7fn9G5SpZSM77
Closed

test: finops formatting — formatBytes and truncateQuery edge cases#390
anandgupta42 wants to merge 3 commits intomainfrom
claude/test-finops-formatting-01AfyN3rkDU7fn9G5SpZSM77

Conversation

@anandgupta42
Copy link
Contributor

@anandgupta42 anandgupta42 commented Mar 23, 2026

Summary

What does this PR do?

1. formatBytes and truncateQuerysrc/altimate/tools/finops-formatting.ts (12 new tests)

These pure utility functions power user-facing output in finops tools (finops-expensive-queries.ts, finops-query-history.ts). Zero tests existed. Testing revealed 5 confirmed bugs:

formatBytes bugs:

  • Negative bytes"NaN undefined" — users see garbage when finops tools compute negative deltas (e.g. comparing periods where usage decreased)
  • NaN input"NaN undefined" — propagated NaN from upstream calculations crashes display
  • Fractional bytes (0.5)"512.00 undefined"Math.floor(Math.log(0.5) / Math.log(1024)) = -1, and units[-1] is undefined

truncateQuery bugs:

  • Whitespace-only input"" (empty string) instead of "(empty)" — the !text guard doesn't catch " " (truthy), but after trim() it becomes "" which is returned directly by the length check
  • maxLen < 3 → output exceeds maxLen — slice(0, 2-3) = slice(0, -1) keeps most of the string, then "..." is appended, producing 13+ chars for a 2-char limit

New coverage includes:

  • Normal cases: zero bytes, exact unit boundaries (B/KB/MB/GB), non-boundary values
  • Normal cases: empty input, short text passthrough, long text truncation, multiline collapse
  • Bug-documenting tests: all 5 bugs above with explanatory comments for future fixers

Type of change

  • New feature (non-breaking change which adds functionality)

Issue for this PR

N/A — proactive test coverage via /test-discovery

How did you verify your code works?

bun test test/altimate/tools/finops-formatting.test.ts    # 12 pass, 0 fail

Checklist

  • 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

https://claude.ai/code/session_01AfyN3rkDU7fn9G5SpZSM77

Summary by CodeRabbit

  • Bug Fixes

    • Improved byte formatting display for non-finite, negative, fractional and boundary values; units now format consistently.
    • Query truncation behavior refined: whitespace-only input shows "(empty)", multiline SQL is collapsed to one line, and very small/non‑positive length limits are handled predictably.
  • Tests

    • Added comprehensive tests covering normal and edge-case scenarios for both formatting behaviors.

Documents 5 confirmed bugs in finops-formatting.ts that affect user-facing
output: negative bytes, NaN, fractional bytes, whitespace-only queries, and
truncation exceeding maxLen.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

https://claude.ai/code/session_01AfyN3rkDU7fn9G5SpZSM77
Copy link

@claude claude bot left a comment

Choose a reason for hiding this comment

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

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review to trigger a review.

Tip: disable this comment in your organization's Code Review settings.

@coderabbitai
Copy link

coderabbitai bot commented Mar 23, 2026

📝 Walkthrough

Walkthrough

Adds a Bun test suite for finops-formatting and small logic updates to formatBytes and truncateQuery in the finops-formatting utility; tests validate normal and edge-case behavior for both functions.

Changes

Cohort / File(s) Summary
Tests
packages/opencode/test/altimate/tools/finops-formatting.test.ts
New Bun test suite covering formatBytes and truncateQuery across normal cases and multiple edge cases (NaN/Infinity, negative and fractional bytes, whitespace-only input, small/zero/negative maxLen, multiline SQL, truncation length constraints).
Utility Implementation
packages/opencode/src/altimate/tools/finops-formatting.ts
Small logic changes: formatBytes returns "0 B" for non-finite inputs, uses absolute value and clamps unit index; truncateQuery treats whitespace-only strings as "(empty)", handles non-positive maxLen and very small maxLen (<4) specially before applying truncation/ellipsis. Relevant areas to review: numeric edge handling, index clamping, and truncation boundary logic.

Estimated Code Review Effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 Hopping through bytes and SQL with cheer,

I round and truncate without fear,
NaN tamed, long queries made neat,
Tests patter quick feet to repeat,
A rabbit's stamp — code checks complete.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
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 (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main changes: adding tests for edge cases in finops formatting utilities.
Description check ✅ Passed The description provides comprehensive coverage: detailed summary of what changed and why (5 confirmed bugs documented), test plan confirming tests pass locally, and checklist items completed. All template sections are addressed.

✏️ 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 claude/test-finops-formatting-01AfyN3rkDU7fn9G5SpZSM77

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/opencode/test/altimate/tools/finops-formatting.test.ts (1)

51-56: Consider asserting exact length for the truncation test.

The truncation logic for maxLen=20 should produce exactly 20 characters (17 from slice + 3 for "..."). While toBeLessThanOrEqual(20) is correct, a stricter assertion would catch if the implementation under-truncates.

💡 Optional: Use exact length assertion
   test("long text truncated with ellipsis", () => {
     const long = "SELECT * FROM very_long_table_name WHERE id = 1"
     const result = truncateQuery(long, 20)
-    expect(result.length).toBeLessThanOrEqual(20)
+    expect(result.length).toBe(20)
     expect(result).toEndWith("...")
   })
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/opencode/test/altimate/tools/finops-formatting.test.ts` around lines
51 - 56, The test "long text truncated with ellipsis" currently uses a
non-strict length check; change the assertion for truncateQuery(long, 20) to
expect exact length 20 (e.g., expect(result.length).toBe(20)) and keep the
expect(result).toEndWith("...") to ensure the function returns the 17-char slice
plus the 3-char ellipsis; update the test for truncateQuery accordingly so it
fails if the function under- or over-truncates.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/opencode/test/altimate/tools/finops-formatting.test.ts`:
- Around line 51-56: The test "long text truncated with ellipsis" currently uses
a non-strict length check; change the assertion for truncateQuery(long, 20) to
expect exact length 20 (e.g., expect(result.length).toBe(20)) and keep the
expect(result).toEndWith("...") to ensure the function returns the 17-char slice
plus the 3-char ellipsis; update the test for truncateQuery accordingly so it
fails if the function under- or over-truncates.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 60b5d1e2-5b90-4795-bcaa-09bc81c63501

📥 Commits

Reviewing files that changed from the base of the PR and between 8d5804f and 5fd6316.

📒 Files selected for processing (1)
  • packages/opencode/test/altimate/tools/finops-formatting.test.ts

anandgupta42 and others added 2 commits March 22, 2026 18:29
`formatBytes`:
- Guard `NaN`/`Infinity` with `Number.isFinite()` → returns "0 B"
- Use `Math.abs()` for log calculation to handle negative byte deltas
- Clamp unit index with `Math.max(0, Math.min(...))` to prevent
  `units[-1]` (fractional bytes) and overflow beyond PB

`truncateQuery`:
- Check post-trim result for empty string → return "(empty)"
- Guard `maxLen <= 0` to prevent `slice(0, negative)` leaking content
- Guard `maxLen < 4` to hard-truncate without ellipsis

Tests updated from documenting bugs to asserting correct behavior.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/opencode/src/altimate/tools/finops-formatting.ts (1)

14-16: Consider the interaction between whitespace-only input and small maxLen.

The current check order means whitespace-only input returns "(empty)" (7 characters) regardless of maxLen, which could exceed the requested length. For example, truncateQuery(" ", 2) returns "(empty)" instead of respecting the 2-character limit.

Given the production callers use maxLen values of 80 and 100 (per the relevant snippets), this is unlikely to cause issues in practice. If this behavior is intentional—treating "(empty)" as a semantic marker that takes precedence over length constraints—it would be helpful to add a brief comment documenting this design choice.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/opencode/src/altimate/tools/finops-formatting.ts` around lines 14 -
16, Reorder the early-return checks in truncateQuery so maxLen constraints are
enforced before returning the "(empty)" marker: move the maxLen checks (maxLen
<= 0 and maxLen < 4) above the oneLine emptiness check (the if (!oneLine) return
"(empty)") so whitespace-only inputs are truncated to respect maxLen;
alternatively, if the "(empty)" marker is intended to take precedence, add a
short comment next to the if (!oneLine) branch explaining that design choice.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/opencode/src/altimate/tools/finops-formatting.ts`:
- Around line 14-16: Reorder the early-return checks in truncateQuery so maxLen
constraints are enforced before returning the "(empty)" marker: move the maxLen
checks (maxLen <= 0 and maxLen < 4) above the oneLine emptiness check (the if
(!oneLine) return "(empty)") so whitespace-only inputs are truncated to respect
maxLen; alternatively, if the "(empty)" marker is intended to take precedence,
add a short comment next to the if (!oneLine) branch explaining that design
choice.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 6c43f44a-b1d0-4688-b98a-9fa09bbecf6b

📥 Commits

Reviewing files that changed from the base of the PR and between 5fd6316 and a3fe7ef.

📒 Files selected for processing (2)
  • packages/opencode/src/altimate/tools/finops-formatting.ts
  • packages/opencode/test/altimate/tools/finops-formatting.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/opencode/test/altimate/tools/finops-formatting.test.ts

anandgupta42 added a commit that referenced this pull request Mar 23, 2026
Merges 9 test PRs (#390, #394, #395, #396, #397, #398, #399, #401, #387)
into a single PR, discarding 4 duplicates (#391, #392, #393, #400).

**New test coverage:**
- `id.test.ts` — 14 tests: Identifier generation, monotonic ordering, timestamp extraction, Zod schema
- `shell.test.ts` — 9 tests: shell blacklist enforcement for fish/nu, cache reset, fallback
- `path-traversal.test.ts` — 7 tests (new): `Protected.isSensitiveWrite` for .pem/.key, .gnupg, .env variants
- `ignore.test.ts` — 7 tests (new): `FileIgnore.match` directory patterns, globs, whitelist overrides
- `paths-parsetext.test.ts` — 16 tests: `ConfigPaths.parseText` env/file substitution, JSONC parsing
- `finops-formatting.test.ts` — 14 tests: `formatBytes`/`truncateQuery` edge cases
- `finops-role-access.test.ts` — 10 tests: RBAC `formatGrants`/`formatHierarchy`/`formatUserRoles`
- `tool-lookup.test.ts` — 4 tests: Zod schema introspection for tool parameters
- `summary-git-path.test.ts` — 10 tests: `unquoteGitPath` decoding for non-ASCII filenames
- `tracing.test.ts` — 2 tests (added): Recap loop detection boundaries
- `patch.test.ts` — 9 tests (added): `maybeParseApplyPatchVerified` entry point coverage
- `instruction.test.ts` — 13 tests (new): `InstructionPrompt.loaded()` dedup guards
- `message-v2.test.ts` — 23 tests (new): `MessageV2.filterCompacted()` boundary detection

**Bug fixes (discovered during testing):**
- `finops-formatting.ts`: fix `formatBytes` crash on negative/NaN/fractional inputs
- `finops-formatting.ts`: fix `truncateQuery` returning empty for whitespace-only, exceeding `maxLen` when < 4
- `training-import.test.ts`: fix pre-existing typecheck errors (missing `context`/`rule` mock keys)
- `instruction.test.ts`, `message-v2.test.ts`: fix `MessageV2.Part` cast and branded ID type errors

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@anandgupta42
Copy link
Contributor Author

Consolidated into #403

@anandgupta42 anandgupta42 deleted the claude/test-finops-formatting-01AfyN3rkDU7fn9G5SpZSM77 branch March 23, 2026 17:11
anandgupta42 added a commit that referenced this pull request Mar 23, 2026
* test: consolidated test coverage across 9 modules (133 new tests)

Merges 9 test PRs (#390, #394, #395, #396, #397, #398, #399, #401, #387)
into a single PR, discarding 4 duplicates (#391, #392, #393, #400).

**New test coverage:**
- `id.test.ts` — 14 tests: Identifier generation, monotonic ordering, timestamp extraction, Zod schema
- `shell.test.ts` — 9 tests: shell blacklist enforcement for fish/nu, cache reset, fallback
- `path-traversal.test.ts` — 7 tests (new): `Protected.isSensitiveWrite` for .pem/.key, .gnupg, .env variants
- `ignore.test.ts` — 7 tests (new): `FileIgnore.match` directory patterns, globs, whitelist overrides
- `paths-parsetext.test.ts` — 16 tests: `ConfigPaths.parseText` env/file substitution, JSONC parsing
- `finops-formatting.test.ts` — 14 tests: `formatBytes`/`truncateQuery` edge cases
- `finops-role-access.test.ts` — 10 tests: RBAC `formatGrants`/`formatHierarchy`/`formatUserRoles`
- `tool-lookup.test.ts` — 4 tests: Zod schema introspection for tool parameters
- `summary-git-path.test.ts` — 10 tests: `unquoteGitPath` decoding for non-ASCII filenames
- `tracing.test.ts` — 2 tests (added): Recap loop detection boundaries
- `patch.test.ts` — 9 tests (added): `maybeParseApplyPatchVerified` entry point coverage
- `instruction.test.ts` — 13 tests (new): `InstructionPrompt.loaded()` dedup guards
- `message-v2.test.ts` — 23 tests (new): `MessageV2.filterCompacted()` boundary detection

**Bug fixes (discovered during testing):**
- `finops-formatting.ts`: fix `formatBytes` crash on negative/NaN/fractional inputs
- `finops-formatting.ts`: fix `truncateQuery` returning empty for whitespace-only, exceeding `maxLen` when < 4
- `training-import.test.ts`: fix pre-existing typecheck errors (missing `context`/`rule` mock keys)
- `instruction.test.ts`, `message-v2.test.ts`: fix `MessageV2.Part` cast and branded ID type errors

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address code review findings — test artifact leakage and cleanup

- summary-git-path.test.ts: use tmpdir() instead of projectRoot to prevent
  Storage.write() from polluting the developer's .opencode/storage/ directory
- finops-role-access.test.ts: consolidate duplicate afterAll hooks to ensure
  ALTIMATE_TELEMETRY_DISABLED env var is cleaned up after tests

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants