Skip to content

RHIDP-14306: add saved prompts data access layer#2166

Open
Jdubrick wants to merge 8 commits into
lightspeed-core:mainfrom
Jdubrick:add-saved-prompts-dal
Open

RHIDP-14306: add saved prompts data access layer#2166
Jdubrick wants to merge 8 commits into
lightspeed-core:mainfrom
Jdubrick:add-saved-prompts-dal

Conversation

@Jdubrick

@Jdubrick Jdubrick commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Description

  • Adds creating, fetching, and deleting items from the saved prompts table based on user id

Note: Endpoints will be added in future PRs

Type of change

  • Refactor
  • New feature
  • Bug fix
  • CVE fix
  • Optimization
  • Documentation Update
  • Configuration Update
  • Bump-up service version
  • Bump-up dependent library
  • Bump-up library or tool used for development (does not change the final image)
  • CI configuration change
  • Konflux configuration change
  • Unit tests improvement
  • Integration tests improvement
  • End to end tests improvement
  • Benchmarks improvement

Tools used to create PR

Identify any AI code assistants used in this PR (for transparency and review context)

  • Assisted-by: Grok 4.5
  • Generated by: Grok 4.5

Related Tickets & Documents

Checklist before requesting a review

  • I have performed a self-review of my code.
  • PR has passed all pre-merge test jobs.
  • If it is a core feature, I have added thorough tests.

Testing

  • Please provide detailed steps to perform tests related to this code change.
  • How were the fix/results from this change verified? Please provide relevant screenshots or results.

Summary by CodeRabbit

  • New Features

    • Added saved-prompt creation with per-user quota enforcement.
    • Added validation for prompt names and content.
    • Added listing of saved prompts, ordered by newest first.
    • Added deletion with ownership checks.
    • Added clear errors for quota limits, missing prompts, access restrictions, and duplicate names.
  • Bug Fixes

    • Improved handling of duplicate saved prompts and missing records.
    • Ensured newly created prompts return complete timestamp information.

Jdubrick added 7 commits July 17, 2026 15:01
Signed-off-by: Jordan Dubrick <jdubrick@redhat.com>
Signed-off-by: Jordan Dubrick <jdubrick@redhat.com>
Signed-off-by: Jordan Dubrick <jdubrick@redhat.com>
Signed-off-by: Jordan Dubrick <jdubrick@redhat.com>
Signed-off-by: Jordan Dubrick <jdubrick@redhat.com>
Signed-off-by: Jordan Dubrick <jdubrick@redhat.com>
Signed-off-by: Jordan Dubrick <jdubrick@redhat.com>
@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Jdubrick, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 41 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9132c345-320b-41fd-b59b-cb1a950d951b

📥 Commits

Reviewing files that changed from the base of the PR and between a00f750 and 983d398.

📒 Files selected for processing (2)
  • src/utils/saved_prompts.py
  • tests/unit/utils/test_saved_prompts.py

Walkthrough

The saved-prompt module now defines shared domain errors, validates quota, names, and content, and provides SQLAlchemy-backed create, list, and ownership-checked delete operations. Unit tests now cover persistence, conflicts, ordering, quotas, timestamps, and access control.

Changes

Saved prompt domain

Layer / File(s) Summary
Validation contracts and domain errors
src/utils/saved_prompts.py, tests/unit/utils/test_saved_prompts.py
Adds shared saved-prompt exception types and validation for quota, normalized display names, and non-empty bounded content.
Saved prompt persistence operations
src/utils/saved_prompts.py, tests/unit/utils/test_saved_prompts.py
Adds create, per-user listing, and ownership-checked deletion with conflict and access errors, plus database-backed coverage for persistence, timestamps, ordering, and failure cases.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested reviewers: tisnik


Important

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

❌ Failed checks (1 error)

Check name Status Explanation Resolution
Performance And Algorithmic Complexity ❌ Error src/utils/saved_prompts.py:177-193 uses .all() with no limit/pagination, so listing prompts can grow unbounded for users with many records. Add a hard limit or cursor/offset pagination to list_saved_prompts_by_user (or its API caller) and return only a bounded page per request.
✅ Passed checks (6 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: adding a saved prompts data access layer.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Security And Secret Handling ✅ Passed PASS: src/utils/saved_prompts.py:13-229 only uses ORM queries and generic logs; no secrets, raw SQL, traversal, or sensitive data leakage; no new endpoints.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
✨ Simplify code
  • Create PR with simplified code

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
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🤖 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 `@src/utils/saved_prompts.py`:
- Around line 177-193: Update list_saved_prompts_by_user to prevent unbounded
result materialization by adding cursor-based pagination or an enforced hard
limit directly to this query. Preserve filtering by user_id and descending
created_at ordering, and ensure the protection is independent of write-path
quota enforcement.
- Around line 147-159: Update the saved-prompt creation flow around
validate_saved_prompt_quota and session.commit to make quota enforcement atomic
under concurrent requests. Serialize quota checks and inserts per user, or
enforce the limit with a database counter/serializable transaction and retry
conflicts, ensuring concurrent creates cannot exceed max_prompts_per_user.
- Around line 128-156: Update the public create path around the SavedPrompt
construction to validate and normalize name and content before persistence,
rather than storing raw caller values. Reuse the established saved-prompt
validators, ensuring blank and oversized values are rejected and names such as
"name" and " name " normalize identically before quota checking and insertion.
- Around line 158-165: Update the IntegrityError handling around session.commit
in the saved-prompt creation flow to translate only violations of the
uq_saved_prompt_user_name constraint into SavedPromptConflictError. Inspect the
exception for that constraint, preserving the existing conflict log and error
mapping when present, and re-raise any other IntegrityError unchanged.

In `@tests/unit/utils/test_saved_prompts.py`:
- Around line 62-63: Add a Google-style docstring to the nested _get_session
function documenting that it creates and returns a Session, including a Returns:
section with the Session type. Keep the existing session_factory() behavior
unchanged.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 86ed8d71-d62c-4b1d-a6b8-69cba8b3087a

📥 Commits

Reviewing files that changed from the base of the PR and between 938dcac and a00f750.

📒 Files selected for processing (2)
  • src/utils/saved_prompts.py
  • tests/unit/utils/test_saved_prompts.py
📜 Review details
⏰ Context from checks skipped due to timeout. (15)
  • GitHub Check: black
  • GitHub Check: unit_tests (3.13)
  • GitHub Check: unit_tests (3.12)
  • GitHub Check: bandit
  • GitHub Check: integration_tests (3.12)
  • GitHub Check: integration_tests (3.13)
  • GitHub Check: build-pr
  • GitHub Check: Pylinter
  • GitHub Check: E2E: server mode / ci / group 1
  • GitHub Check: E2E: library mode / ci / group 1
  • GitHub Check: E2E: library mode / ci / group 3
  • GitHub Check: E2E: server mode / ci / group 3
  • GitHub Check: E2E: library mode / ci / group 2
  • GitHub Check: E2E: server mode / ci / group 2
  • GitHub Check: E2E Tests for Lightspeed Evaluation job
🧰 Additional context used
📓 Path-based instructions (6)
**/*

📄 CodeRabbit inference engine (Custom checks)

**/*: Flag meaningful O(n^2)+ algorithms on non-trivial inputs, including handlers and Kubernetes list operations.
Flag N+1 patterns that list items and then query once per item, including Kubernetes API and database access.
Flag expensive work inside loops, including API calls, JSON parsing, and regex compilation.
Flag unbounded growth in caches, watchers, or buffers when eviction or limits are missing.
Flag missing pagination or limits on list operations and API endpoints.
Flag secrets or tokens logged in plaintext or hardcoded in source.
Flag API endpoints missing authentication or authorization.
Flag injection vulnerabilities, including SQL injection, command injection, and path traversal.
Flag sensitive data leaked in API responses, WebSocket messages, or logs.
Flag Kubernetes Secrets and Red Hat secrets missing OwnerReferences.

Files:

  • tests/unit/utils/test_saved_prompts.py
  • src/utils/saved_prompts.py
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: Use absolute imports for internal Python modules.
Start every module with a descriptive docstring and use logger = get_logger(__name__) for module logging.
Define shared constants in the central constants.py module, use descriptive comments, and annotate constants with Final[type].
Use complete type annotations for function parameters and return values, modern union syntax, and typing_extensions.Self for model validators.
Document all modules, classes, and functions using Google-style Python docstrings, including applicable Parameters, Returns, Raises, and Attributes sections.
Use descriptive snake_case, action-oriented function names such as get_, validate_, and check_.
Avoid modifying input parameters in place; return a newly created data structure instead.
Use async def for I/O operations and external API calls.
Use standard logger levels appropriately: debug for diagnostics, info for normal execution, warning for unexpected conditions, and error for serious failures.
Name classes with PascalCase and use descriptive suffixes such as Configuration, Error/Exception, Resolver, and Interface where applicable.
Use ABC and @abstractmethod for abstract interfaces; provide complete, specific type annotations for class attributes and avoid Any.

Files:

  • tests/unit/utils/test_saved_prompts.py
  • src/utils/saved_prompts.py
tests/unit/**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

Use pytest for unit tests, shared fixtures in conftest.py, pytest-mock for mocks, and pytest.mark.asyncio for asynchronous tests; do not use unittest.

Files:

  • tests/unit/utils/test_saved_prompts.py
tests/**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

Maintain at least 60% unit-test coverage and 10% integration-test coverage.

Files:

  • tests/unit/utils/test_saved_prompts.py
**/*.{py,yaml,yml,json,toml}

📄 CodeRabbit inference engine (AGENTS.md)

Never commit secrets or keys; use environment variables for sensitive data.

Files:

  • tests/unit/utils/test_saved_prompts.py
  • src/utils/saved_prompts.py
src/**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

Configuration models must extend ConfigurationBase, whose extra="forbid" behavior rejects unknown fields; use types such as Optional[FilePath], PositiveInt, and SecretStr where appropriate.

Files:

  • src/utils/saved_prompts.py
🧠 Learnings (2)
📚 Learning: 2026-06-24T13:45:37.249Z
Learnt from: Jdubrick
Repo: lightspeed-core/lightspeed-stack PR: 1971
File: src/utils/markdown_repair.py:31-36
Timestamp: 2026-06-24T13:45:37.249Z
Learning: In the lightspeed-stack repository, docstrings must use the section header name "Parameters:" (not "Args:") for function arguments, even if the project references Google Python docstring conventions. Ensure docstrings follow the project’s established "Parameters:" header format for any documented function parameters.

Applied to files:

  • tests/unit/utils/test_saved_prompts.py
  • src/utils/saved_prompts.py
📚 Learning: 2026-07-06T15:26:18.398Z
Learnt from: Jdubrick
Repo: lightspeed-core/lightspeed-stack PR: 2071
File: src/models/config.py:2416-2422
Timestamp: 2026-07-06T15:26:18.398Z
Learning: In this repo’s Python code under src/**, don’t treat differences in string concatenation style as a style inconsistency when Black has effectively forced (or made clearer) use of explicit `+` string concatenation in multi-line logger/string expressions. If adjacent-literal implicit concatenation is avoided/changed specifically to accommodate Black’s formatting in these call sites, accept the `+` usage and don’t recommend converting it solely for consistency with nearby blocks that use implicit concatenation.

Applied to files:

  • src/utils/saved_prompts.py
🔇 Additional comments (3)
src/utils/saved_prompts.py (2)

1-58: LGTM!

Also applies to: 61-117


120-174: 🩺 Stability & Availability

Keep this DAL synchronous. src/utils/saved_prompts.py is built on get_session() -> Session; there’s no AsyncSession path for this code, so the async-session refactor doesn’t apply here.

			> Likely an incorrect or invalid review comment.
tests/unit/utils/test_saved_prompts.py (1)

1-61: LGTM!

Also applies to: 65-67, 236-376

Comment thread src/utils/saved_prompts.py
Comment thread src/utils/saved_prompts.py
Comment on lines +158 to +165
try:
session.commit()
except IntegrityError as exc:
logger.debug(
"Saved prompt create conflict for user_id=%s",
user_id,
)
raise SavedPromptConflictError("Saved prompt name already exists") from exc

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
ast-grep outline src/models/database/saved_prompts.py --items all
rg -nC4 'UniqueConstraint|unique=|ForeignKey|saved.prompt' \
  src/models/database/saved_prompts.py
fd -a -t f -i 'saved.*prompt' . \
  -x rg -nC3 'unique|constraint|user_id|name' {}

Repository: lightspeed-core/lightspeed-stack

Length of output: 25310


Handle only the saved-prompt uniqueness violation here. This maps every IntegrityError to SavedPromptConflictError, so primary-key or other database failures are reported as duplicate names. Check for uq_saved_prompt_user_name and re-raise any other IntegrityError.

🤖 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 `@src/utils/saved_prompts.py` around lines 158 - 165, Update the IntegrityError
handling around session.commit in the saved-prompt creation flow to translate
only violations of the uq_saved_prompt_user_name constraint into
SavedPromptConflictError. Inspect the exception for that constraint, preserving
the existing conflict log and error mapping when present, and re-raise any other
IntegrityError unchanged.

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.

Using UUID4 for the key here makes it extremely unlikely that we have a collision (if not almost impossible) on the PK field. The only other error that could be raised in that case is the duplicate name.

Comment thread src/utils/saved_prompts.py
Comment thread tests/unit/utils/test_saved_prompts.py
Signed-off-by: Jordan Dubrick <jdubrick@redhat.com>
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