Skip to content

Fix/include default branch for session category switch - #25

Merged
aaronbrethorst merged 3 commits into
OneBusAway:mainfrom
JohnAkindipe:fix/include-default-branch-for-sessionCategory-switch
Sep 25, 2026
Merged

aaronbrethorst merged 3 commits into
OneBusAway:mainfrom
JohnAkindipe:fix/include-default-branch-for-sessionCategory-switch

Conversation

@JohnAkindipe

@JohnAkindipe JohnAkindipe commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #19

  • Added explicit default branches to switches that handle sessionCategory to provide clear fallback behavior and better debugging information and as general best practice.
  • Enabled the exhaustive check for golangci-lint in the Makefile.
  • Added comment clarifying zero-valued sessionCategory maps to "disambiguation".
  • Tests pass, but enabling the exhaustive linter revealed unrelated non-exhaustive switches elsewhere (listed below).

Reasoning for default case logic

setSession()
Returning an error for unknown sessionCategory prevents silent behavior and forces the caller to handle unexpected input instead of continuing with storing an entry with no timestamps. The error formatting is consistent with that in String() to allow for easy debugging.

estimateMemoryUsage()
Decided to add a conservative fallback memory estimate (baseSize += 150) for unknown types. Only a rough estimate and added for completeness sake

ExpireSession()
Decide to opt for a fail-fast approach and panic when an unknown sessionCategory type is supplied. Error formatting is also consistent with that in String() for easier debugging.

Other notes

The fmt.Fprintf changes in formatters/response.go are small performance/clarity improvements (avoid temp string allocation).

Testing

  • Ran make fmt, make vet, make lint, make test
  • All tests pass.

Notes

make lint (with -E exhaustive) reported remaining non-exhaustive switches in other files. These are unrelated to the sessionCategory changes, but surfaced after enabling the exhaustive check:

  • handlers/common/errors.go:267:3: missing cases in switch of type models.ErrorCode: ErrorCodeInvalidStopID, ErrorCodeStopNotFound, ErrorCodeInvalidResponse, ErrorCodeValidationFailed, ErrorCodeInternalError (exhaustive)
  • client/onebusaway.go:152:2: missing cases in switch of type client.CircuitState: CircuitClosed (exhaustive)

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of unexpected session states, providing clearer error information and preventing invalid state transitions.
    • Enhanced diagnostic output for unrecognized session categories.
  • Chores
    • Strengthened code-quality checks to identify additional exhaustive cases during validation.
    • Streamlined response formatting while preserving existing message content and presentation.

@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Review Change Stack

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: f18573e0-4454-47d6-bf94-e10c39e8ce69

📝 Walkthrough

Walkthrough

The PR enables exhaustive linting, replaces intermediate formatted strings with direct builder writes, and adds explicit unknown-category handling across session storage and expiration logic.

Changes

Lint configuration

Layer / File(s) Summary
Exhaustive lint target
Makefile
The lint target now runs golangci-lint with the exhaustive analyzer enabled.

Response formatting

Layer / File(s) Summary
Direct formatted response writes
formatters/response.go
SMS and disambiguation responses use fmt.Fprintf while preserving existing output formats.

Session category handling

Layer / File(s) Summary
Explicit unknown-category handling
handlers/common/session_store.go
Unknown session categories now receive diagnostic string output and explicit error, estimate, or panic behavior across session operations.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested reviewers: hubertgoeuropa

🚥 Pre-merge checks | ✅ 4 | ❌ 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 (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title matches the main change: adding default branches to session category switches for safer fallback behavior.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@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: 2

🤖 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 `@handlers/common/session_store.go`:
- Around line 319-320: Validate sessionType before entering the capacity and
eviction logic in evictLRUSessions, reusing the existing category validation and
unknown-sessionCategory error behavior. Ensure invalid categories return without
deleting valid sessions, and add a regression test covering an invalid category
when the store is at capacity.

In `@Makefile`:
- Line 38: Before enabling exhaustive in the Makefile lint target, resolve or
explicitly exclude the known findings in handlers/common/errors.go and
client/onebusaway.go, then update the golangci-lint invocation in
.github/workflows/ci.yml to enforce the same exhaustive check as make lint.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: df53e1ef-5863-4f57-8121-955f03d62acb

📥 Commits

Reviewing files that changed from the base of the PR and between 8d5bf34 and 33ced29.

📒 Files selected for processing (3)
  • Makefile
  • formatters/response.go
  • handlers/common/session_store.go

Comment on lines +319 to +320
default:
return fmt.Errorf("unknown sessionCategory(%d)", int(sessionType))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate sessionType before evicting sessions.

When the store is at capacity, evictLRUSessions runs before this error branch. An invalid category can therefore return an error while still deleting valid sessions. Validate the category before the capacity/eviction logic and add a regression test for this failure path.

Proposed fix
 func (s *ImprovedSessionStore) setSession(phoneNumber string, data interface{}, sessionType sessionCategory) error {
 	if !phoneRegex.MatchString(phoneNumber) {
 		return fmt.Errorf("invalid phone number format: %s", phoneNumber)
 	}
+	if sessionType != disambiguation && sessionType != voice && sessionType != sms {
+		return fmt.Errorf("unknown sessionCategory(%d)", int(sessionType))
+	}
 
 	s.mutex.Lock()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
default:
return fmt.Errorf("unknown sessionCategory(%d)", int(sessionType))
func (s *ImprovedSessionStore) setSession(phoneNumber string, data interface{}, sessionType sessionCategory) error {
if !phoneRegex.MatchString(phoneNumber) {
return fmt.Errorf("invalid phone number format: %s", phoneNumber)
}
if sessionType != disambiguation && sessionType != voice && sessionType != sms {
return fmt.Errorf("unknown sessionCategory(%d)", int(sessionType))
}
s.mutex.Lock()
🤖 Prompt for 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.

In `@handlers/common/session_store.go` around lines 319 - 320, Validate
sessionType before entering the capacity and eviction logic in evictLRUSessions,
reusing the existing category validation and unknown-sessionCategory error
behavior. Ensure invalid categories return without deleting valid sessions, and
add a regression test covering an invalid category when the store is at
capacity.

Comment thread Makefile Outdated
# Lint the code (requires golangci-lint)
lint:
golangci-lint run
golangci-lint run -E exhaustive

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Do not enable a failing lint gate without aligning CI and existing violations.

make lint now fails on the known non-exhaustive switches in handlers/common/errors.go and client/onebusaway.go. Fix or explicitly exclude those findings before enabling this flag; additionally, .github/workflows/ci.yml runs golangci-lint without -E exhaustive, so CI currently does not enforce the same check.

🤖 Prompt for 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.

In `@Makefile` at line 38, Before enabling exhaustive in the Makefile lint target,
resolve or explicitly exclude the known findings in handlers/common/errors.go
and client/onebusaway.go, then update the golangci-lint invocation in
.github/workflows/ci.yml to enforce the same exhaustive check as make lint.

@aaronbrethorst

Copy link
Copy Markdown
Member

Code review

Found 1 issue:

  1. Enabling -E exhaustive leaves make lint failing. The PR body itself reports two remaining findings (handlers/common/errors.go:267 over models.ErrorCode, client/onebusaway.go:152 over client.CircuitState), and both are confirmed on this branch — the repo has no .golangci.yml, so default-signifies-exhaustive is off and a default: arm does not satisfy the analyzer. CI won't surface it either: .github/workflows/ci.yml runs golangci-lint-action directly rather than make lint, so CI stays green while the required local command is red. CLAUDE.md says "Before saying your work is finished, you must always run these commands and ensure they pass: make lint". Either fix/exclude those two switches in the same PR, or drop the Makefile change and keep just the default: arms (issue Harden sessionCategory switches against future categories #19 offered these as alternatives, not a package deal).

twilio/Makefile

Lines 36 to 39 in 33ced29

# Lint the code (requires golangci-lint)
lint:
golangci-lint run -E exhaustive

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

@aaronbrethorst aaronbrethorst left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for this — the Go changes are exactly what #19 asked for, and I like the choices you made. Returning an error from setSession rather than storing a half-initialized entry is right, the sessionCategory(%d) fallback in String() is more diagnosable than "unknown", and panicking in ExpireSession is fine by me: it's a test-only helper, and #19 explicitly sanctioned panicking there. The fmt.Fprintf conversions in formatters/response.go also clear three real staticcheck QF1012 warnings, which is a nice bonus.

One blocker, and it's the Makefile line.

golangci-lint run -E exhaustive leaves make lint failing. Running it against the tree:

client/onebusaway.go:152:2: missing cases in switch of type client.CircuitState: client.CircuitClosed (exhaustive)
handlers/common/errors.go:267:3: missing cases in switch of type models.ErrorCode: models.ErrorCodeInvalidStopID, models.ErrorCodeStopNotFound, models.ErrorCodeInvalidResponse, models.ErrorCodeValidationFailed, models.ErrorCodeInternalError (exhaustive)

You listed both in your PR notes, so this isn't news — but CLAUDE.md requires make lint to pass, so we can't land it red. Two details make this easy to miss: there's no .golangci.yml in the repo, so default-signifies-exhaustive stays false and the default: arms already present in those two switches don't silence the analyzer; and CI's lint job runs golangci-lint-action directly rather than make lint, so CI stays green while the required command is red.

Either fix works for me:

  1. Drop the -E exhaustive line and land the default: arms on their own. #19 offered the analyzer and the explicit defaults as alternatives, so this still fully closes the issue.
  2. Keep the analyzer and fix the two switches — add case CircuitClosed: to the circuit-breaker switch and the five missing models.ErrorCode cases to IsRetryableError. Both are a few lines. If you go this way, it's worth pointing CI at make lint in the same PR so the two can't drift apart again.

I'd lean toward (1) here and (2) as a follow-up, but I'm happy with either. Ping me and I'll re-review as soon as it's updated.

@JohnAkindipe

Copy link
Copy Markdown
Contributor Author

@aaronbrethorst this is ready for re-review. I went with option 1 and removed the -E exhaustive flag from the make lint target.

This keeps the defensive default branches in place while allowing make lint to pass without requiring every enum-like switch to explicitly list all cases.

@aaronbrethorst aaronbrethorst left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for the quick turnaround. Dropping -E exhaustive was the right call; make lint is clean again and the default: arms stand on their own, which fully closes #19. Approving and merging.

@aaronbrethorst
aaronbrethorst merged commit 4a372fd into OneBusAway:main Sep 25, 2026
5 checks passed
@JohnAkindipe
JohnAkindipe deleted the fix/include-default-branch-for-sessionCategory-switch branch September 25, 2026 11:28
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.

Harden sessionCategory switches against future categories

2 participants