Skip to content

fix(ai): avoid constant oauth token ordering#503

Open
izadoesdev wants to merge 1 commit into
stagingfrom
codex/fix-insights-oauth-order
Open

fix(ai): avoid constant oauth token ordering#503
izadoesdev wants to merge 1 commit into
stagingfrom
codex/fix-insights-oauth-order

Conversation

@izadoesdev

@izadoesdev izadoesdev commented Jun 27, 2026

Copy link
Copy Markdown
Member

Summary

  • Fix OAuth token lookup ordering so the no-preferred-user path does not emit ORDER BY 0.
  • Keep preferred-user ordering before owner/admin role priority.
  • Add a regression test that renders the Postgres SQL fragments and guards this exact shape.

Validation

  • bun test src/ai/tools/utils/oauth-token.test.ts
  • bun run test --filter @databuddy/ai
  • pre-push hook: dotenv -- turbo run test
  • commit hook: dotenv -- turbo run check-types and enforce-format

Summary by cubic

Fix OAuth token ordering to stop emitting ORDER BY 0 when no preferred user is set. We still prefer the requested user first, then owner/admin roles.

  • Bug Fixes

    • When no preferred user is provided, order only by role priority to avoid constant sorting.
    • Added a regression test that asserts the exact Postgres SQL fragments.
  • Refactors

    • Extracted ordering into getOAuthTokenOrderBy and used spread .orderBy(...orderBy) for clarity.

Written for commit 12cecfd. Summary will update on new commits.

Review in cubic

@unkey-deploy

unkey-deploy Bot commented Jun 27, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Unkey Deploy

Name Status Preview Inspect Updated (UTC)
api (preview) Ready Visit Preview Inspect Jun 27, 2026 8:49am

@vercel

vercel Bot commented Jun 27, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
databuddy-status Ready Ready Preview, Comment Jun 27, 2026 8:48am
2 Skipped Deployments
Project Deployment Actions Updated (UTC)
dashboard Skipped Skipped Jun 27, 2026 8:48am
documentation Skipped Skipped Jun 27, 2026 8:48am

@coderabbitai

coderabbitai Bot commented Jun 27, 2026

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: e8ff479c-70e6-46b4-982f-f71f09a89a40

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/fix-insights-oauth-order

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.

@cubic-dev-ai cubic-dev-ai 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.

No issues found across 3 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.
Architecture diagram
sequenceDiagram
    participant AI as AI Tool
    participant OAuth as OAuth Token Service
    participant Ordering as getOAuthTokenOrderBy()
    participant DB as Database

    Note over AI,DB: OAuth Token Resolution Flow

    AI->>OAuth: resolveOAuthToken(preferUserId?, providerId)
    
    alt preferUserId provided
        OAuth->>Ordering: getOAuthTokenOrderBy("user_123")
        Ordering-->>OAuth: [preference CASE, role priority CASE]
    else no preferUserId
        OAuth->>Ordering: getOAuthTokenOrderBy(undefined)
        Ordering-->>OAuth: [role priority CASE only]
    end

    OAuth->>DB: .select(...).orderBy(...orderBy).limit(MAX_CANDIDATES)
    DB-->>OAuth: TokenCandidate[]

    loop for each candidate
        OAuth->>OAuth: Check token validity & TTL
        alt valid token
            OAuth-->>AI: ResolvedToken
        else invalid/expired
            OAuth->>OAuth: continue to next candidate
        end
    end

    alt no valid candidate found
        OAuth-->>AI: null
    end

    Note over Ordering: Key boundary: Ordering logic extracted<br/>ensures no ORDER BY constant (0)<br/>when preferUserId is missing
Loading

Shadow auto-approve: would auto-approve. Fix OAuth token ordering bug when no preferred user is set; extract ordering logic with test coverage.

Re-trigger cubic

@greptile-apps

greptile-apps Bot commented Jun 27, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a bug where omitting preferUserId caused ORDER BY 0 to be emitted in the Postgres query, which is invalid (PostgreSQL column references are 1-based). The fix extracts ordering logic into oauth-token-ordering.ts and returns only [ROLE_PRIORITY] when no user preference is given, dropping the spurious constant expression.

  • oauth-token-ordering.ts (new): Encapsulates the ORDER BY logic; returns 1 expression (role priority) or 2 (user preference + role priority) depending on preferUserId.
  • oauth-token.ts: Removes inline ordering and delegates to the new utility via .orderBy(...orderBy).
  • oauth-token.test.ts (new): Regression tests that render each expression to its Postgres SQL fragment, guarding both the constant-free path and the preferred-user path.

Confidence Score: 5/5

Safe to merge — the change is narrow and well-tested, touching only the ORDER BY construction path for OAuth token lookup.

The diff is a targeted extraction of ordering logic that also closes a real bug: ORDER BY 0 in Postgres is invalid (column references are 1-based) and would have errored on every token lookup where no preferred user was passed. The new utility is straightforward, the spread into .orderBy() is correct, and the regression tests render the actual SQL fragments against both branches. No pre-existing behavior is changed beyond removing the invalid constant from the ORDER BY clause.

No files require special attention — all three are small, focused, and the tests directly validate the SQL output.

Important Files Changed

Filename Overview
packages/ai/src/ai/tools/utils/oauth-token-ordering.ts New utility that correctly returns [ROLE_PRIORITY] when no preferred user is given, avoiding the ORDER BY 0 bug; the module-level ROLE_PRIORITY constant is safe to share as Drizzle's SQL objects are immutable value objects.
packages/ai/src/ai/tools/utils/oauth-token.ts Delegates ordering to the new utility via spread; removes the sql0 fallback and the now-redundant ROLE_PRIORITY constant; logic is otherwise unchanged.
packages/ai/src/ai/tools/utils/oauth-token.test.ts Regression tests render the SQL fragments directly via PgDialect.sqlToQuery; covers both the no-preferred-user path and the user-preference path with correct expected strings.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant Caller
    participant getOAuthToken
    participant resolveOAuthToken
    participant getOAuthTokenOrderBy
    participant DB as Postgres DB

    Caller->>getOAuthToken: (providerId, orgId, preferUserId?)
    getOAuthToken->>resolveOAuthToken: (providerId, orgId, preferUserId?)
    resolveOAuthToken->>getOAuthTokenOrderBy: (preferUserId?)
    alt preferUserId is set
        getOAuthTokenOrderBy-->>resolveOAuthToken: [user_preference_expr, ROLE_PRIORITY]
    else no preferUserId
        getOAuthTokenOrderBy-->>resolveOAuthToken: [ROLE_PRIORITY]
    end
    resolveOAuthToken->>DB: SELECT ... ORDER BY ...orderBy LIMIT 5
    DB-->>resolveOAuthToken: TokenCandidate[]
    resolveOAuthToken-->>getOAuthToken: "ResolvedToken | null"
    getOAuthToken-->>Caller: "string | null"
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant Caller
    participant getOAuthToken
    participant resolveOAuthToken
    participant getOAuthTokenOrderBy
    participant DB as Postgres DB

    Caller->>getOAuthToken: (providerId, orgId, preferUserId?)
    getOAuthToken->>resolveOAuthToken: (providerId, orgId, preferUserId?)
    resolveOAuthToken->>getOAuthTokenOrderBy: (preferUserId?)
    alt preferUserId is set
        getOAuthTokenOrderBy-->>resolveOAuthToken: [user_preference_expr, ROLE_PRIORITY]
    else no preferUserId
        getOAuthTokenOrderBy-->>resolveOAuthToken: [ROLE_PRIORITY]
    end
    resolveOAuthToken->>DB: SELECT ... ORDER BY ...orderBy LIMIT 5
    DB-->>resolveOAuthToken: TokenCandidate[]
    resolveOAuthToken-->>getOAuthToken: "ResolvedToken | null"
    getOAuthToken-->>Caller: "string | null"
Loading

Reviews (1): Last reviewed commit: "fix(ai): avoid constant oauth token orde..." | Re-trigger Greptile

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