Skip to content

feat(core): Add statement timeout parameter.#3544

Open
c-r33d wants to merge 2 commits into
mainfrom
add-statement-timeout
Open

feat(core): Add statement timeout parameter.#3544
c-r33d wants to merge 2 commits into
mainfrom
add-statement-timeout

Conversation

@c-r33d
Copy link
Copy Markdown
Contributor

@c-r33d c-r33d commented May 28, 2026

Note

Adding a query timeout will be useful for protecting the database from
long running searches when substring search is added to the List RPCs.

1.) Add the ability to specify a statement timeout for our queries.
2.) By default we do not specify a timeout, but allow one to be set if needed.

Summary by CodeRabbit

  • New Features
    • Optional database statement timeout setting to limit query execution time.
  • Configuration
    • Example config files updated with a commented example for the new timeout setting.
  • Tests
    • Automated tests updated to validate timeout behavior.

Review Change Stack

@c-r33d c-r33d requested a review from a team as a code owner May 28, 2026 20:33
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a configurable statement timeout for database connections. This enhancement is designed to protect the database from potentially expensive, long-running operations, particularly in anticipation of upcoming substring search functionality in List RPCs. The implementation adds the parameter to the database configuration struct and ensures it is properly handled during connection pool initialization.

Highlights

  • Database Configuration: Added a new statement_timeout parameter to the database configuration, allowing for better control over long-running queries.
  • Configuration Updates: Updated default configuration files (opentdf-core-mode.yaml, opentdf-dev.yaml, opentdf-example.yaml) to include the new timeout setting.
  • Testing: Extended Test_BuildConfig_ConnString to verify that the statement timeout is correctly applied to runtime parameters when configured.
New Features

🧠 You can now enable Memory (public preview) to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.


A query runs, it takes too long, The database feels something's wrong. We set a limit, time to cease, And bring the system back to peace.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 28, 2026

📝 Walkthrough

Walkthrough

Adds an optional DB statement_timeout config field (StatementTimeoutSeconds), emits it in logs, applies it to pgx runtime parameters as "Ns" when >0, updates three YAML examples with a commented setting, and extends tests to validate runtime parameter behavior for unset and 30s cases.

Changes

Database Statement Timeout Configuration

Layer / File(s) Summary
Config struct field and logging
service/pkg/db/db.go
Adds StatementTimeoutSeconds to Config and includes statement_timeout_seconds in LogValue() output.
Conditional parameter application in buildConfig
service/pkg/db/db.go
buildConfig() sets ConnConfig.RuntimeParams["statement_timeout"] to a formatted seconds string when StatementTimeoutSeconds > 0.
Configuration file examples
opentdf-core-mode.yaml, opentdf-dev.yaml, opentdf-example.yaml
Adds commented statement_timeout_seconds: 30 lines to DB/local development sections; also reformats a gRPC port line in opentdf-core-mode.yaml.
Test updates for statement_timeout support
service/pkg/db/db_test.go
Extends test table with wantRuntimeParams, adds cases for unset and 30s, and updates assertions to check presence/absence and exact runtime param values.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I nibbled configs in the night,
A timeout added—soft and light,
Tests hopped in line,
Runtime params fine,
Now queries nap without a fright. 🌙

🚥 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding a statement timeout parameter to the database configuration across all config files and the core db module.
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 add-statement-timeout

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
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a statement_timeout configuration option for database connections, updating the configuration files, the database configuration struct, logging, connection initialization, and corresponding unit tests. The reviewer feedback suggests changing the parameter type from a string to an integer representing seconds (statement_timeout_seconds) to maintain consistency with other timeout settings and prevent PostgreSQL from misinterpreting bare integers as milliseconds. This change requires updating the configuration files, struct fields, logger, connection builder, and tests accordingly.

Comment thread service/pkg/db/db.go Outdated
Comment thread service/pkg/db/db.go Outdated
Comment thread service/pkg/db/db.go Outdated
Comment thread service/pkg/db/db_test.go Outdated
Comment thread opentdf-core-mode.yaml Outdated
Comment thread opentdf-dev.yaml Outdated
Comment thread opentdf-example.yaml Outdated
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 28, 2026

Actionable comments posted: 0

@github-actions
Copy link
Copy Markdown
Contributor

Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 177.42266ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 85.772112ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 434.192937ms
Throughput 230.31 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 43.442906979s
Average Latency 433.219553ms
Throughput 115.09 requests/second

@github-actions
Copy link
Copy Markdown
Contributor

Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 173.836728ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 85.963536ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 441.884153ms
Throughput 226.30 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 42.930605217s
Average Latency 426.932995ms
Throughput 116.47 requests/second

Copy link
Copy Markdown

@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.

Actionable comments posted: 1

🤖 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 `@service/pkg/db/db.go`:
- Around line 255-257: The code currently sets
parsed.ConnConfig.RuntimeParams["statement_timeout"] using
c.StatementTimeoutSeconds which applies a pool-wide timeout and will also affect
migrations/admin work (see migrationInit which casts c.Pgx to *pgxpool.Pool and
uses stdlib.OpenDBFromPool). Remove the RuntimeParams assignment and instead
apply the timeout only where needed: use context.WithTimeout around RPC
handlers/queries that require a per-request timeout (or run "SET LOCAL
statement_timeout = 'Ns'" at the start of the specific transaction) in the
List-query code paths; keep references to c.StatementTimeoutSeconds,
parsed.ConnConfig.RuntimeParams, migrationInit, c.Pgx and stdlib.OpenDBFromPool
to locate the related code.
🪄 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: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3e6ea1cf-a481-40f1-a240-49b167802ede

📥 Commits

Reviewing files that changed from the base of the PR and between 83d9202 and 81ff8de.

📒 Files selected for processing (5)
  • opentdf-core-mode.yaml
  • opentdf-dev.yaml
  • opentdf-example.yaml
  • service/pkg/db/db.go
  • service/pkg/db/db_test.go

Comment thread service/pkg/db/db.go
Comment on lines +255 to +257
if c.StatementTimeoutSeconds > 0 {
parsed.ConnConfig.RuntimeParams["statement_timeout"] = fmt.Sprintf("%ds", c.StatementTimeoutSeconds)
}
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot May 29, 2026

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# How are migrations run? Do they reuse the pool/SQLDB built from buildConfig?
rg -nP --type=go -C4 '\b(RunMigrations|runMigrations|Migrate|migrat)' service/pkg/db
# Find the migration runner entrypoint and what conn/pool it uses
ast-grep --pattern 'func ($_ $_) RunMigrations($$$) { $$$ }'

Repository: opentdf/platform

Length of output: 10075


statement_timeout is pool-wide and will also affect migrations/admin work

The statement_timeout startup runtime param applies to every statement executed via this client’s shared pgxpool.Pool:

  • migrationInit casts c.Pgx to *pgxpool.Pool and creates the migrations DB handle with stdlib.OpenDBFromPool(pool), so Goose runs migrations on connections from the same pool that carries RuntimeParams["statement_timeout"].
  • This means a pool-wide timeout could fail slow startup migrations/backfills, not just the intended List RPC queries.
  • "%ds" formatting is correct for PostgreSQL statement_timeout (unit-suffixed seconds like "30s").
if c.StatementTimeoutSeconds > 0 {
	parsed.ConnConfig.RuntimeParams["statement_timeout"] = fmt.Sprintf("%ds", c.StatementTimeoutSeconds)
}
🤖 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 `@service/pkg/db/db.go` around lines 255 - 257, The code currently sets
parsed.ConnConfig.RuntimeParams["statement_timeout"] using
c.StatementTimeoutSeconds which applies a pool-wide timeout and will also affect
migrations/admin work (see migrationInit which casts c.Pgx to *pgxpool.Pool and
uses stdlib.OpenDBFromPool). Remove the RuntimeParams assignment and instead
apply the timeout only where needed: use context.WithTimeout around RPC
handlers/queries that require a per-request timeout (or run "SET LOCAL
statement_timeout = 'Ns'" at the start of the specific transaction) in the
List-query code paths; keep references to c.StatementTimeoutSeconds,
parsed.ConnConfig.RuntimeParams, migrationInit, c.Pgx and stdlib.OpenDBFromPool
to locate the related code.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is a good point. Should we override this client setting while running migrations? @c-r33d

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, I actually was rethinking how I was going to do this because of the coderabbit comment. The problem is that we run migrations during startup and that uses the pool that where we have already specified. I will check if we can override this with a command-level SET.

@github-actions
Copy link
Copy Markdown
Contributor

⚠️ Govulncheck found vulnerabilities ⚠️

The following modules have known vulnerabilities:

  • examples
  • otdfctl
  • sdk
  • service
  • lib/fixtures
  • tests-bdd

See the workflow run for details.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants