Repository navigation
fix(cache): guard empty repolist and add bounded cache polling - #1219
neo0007777 wants to merge 2 commits into
Conversation
- Short-circuit on empty or None repolist in get_uncached, retrieve_from_cache, and caching_wrapper to prevent PostgreSQL SyntaxError ('IN ()') and TypeError.
- Ensure psycopg2 connections are explicitly closed in try...finally blocks across cache_facade to prevent database connection leaks.
- Safely escape table names using psycopg2.sql.Identifier in retrieve_from_cache.
- Introduce wait_for_cache helper with deadline timeout and exponential backoff.
- Add unit test suite in tests/test_cache_facade.py.
Fixes chaoss#1218
Signed-off-by: Shiva Sharma <shivaumj@gmail.com>
|
Hi @EngCaioFonseca, @cdolfi, @MoralCode - could you please review this PR when you have a moment? Why this is important (in short):
Thank you! |
|
@CodeRabbit full review |
Action performed
|
Findings
|
| Layer / File(s) | Summary |
|---|---|
Cache query handling and connection lifecycle 8Knot/cache_manager/cache_facade.py, tests/test_cache_facade.py, pyproject.toml |
get_uncached and retrieve_from_cache return empty results for empty repository lists. Database connections are closed in finally blocks, and cache reads compose table names with pg_sql.Identifier. Tests cover empty inputs, query results, and connection closure; pytest adds 8Knot to the import path. |
Bounded polling and wrapper input guards 8Knot/cache_manager/cache_facade.py, tests/test_cache_facade.py |
wait_for_cache polls with delays that increase from 0.5 seconds to a 5-second maximum and raises TimeoutError at its deadline. caching_wrapper skips work for empty repository lists and no longer returns 0 when all requested repositories are cached. Tests cover polling, timeout, and empty inputs. |
Estimated code review effort: 3 (Moderate) | ~20 minutes
Change: Bug fix · Severity of issue fixed: Medium
Sequence Diagram(s)
sequenceDiagram
participant wait_for_cache
participant get_uncached
participant CacheDB
loop Until cached or timeout
wait_for_cache->>get_uncached: Check repository IDs
get_uncached->>CacheDB: Query cache bookkeeping
CacheDB-->>get_uncached: Return cached repository IDs
get_uncached-->>wait_for_cache: Return uncached repository IDs
end
Possibly related issues
- Issue 1210: The PR adds cache-read guards and bounded waiting, but does not implement the proposed cached dataset module.
- Issue 1207: The PR guards empty repository lists in the cache facade; the separate direct SQL paths in home metrics are not changed.
- Issue 1148: The PR adds bounded polling with increasing delays, but the summaries do not show migration of existing callback polling loops.
Suggested reviewers: jameskunstle, engcaiofonseca
Merge Risk: 
Low · up to 4c3ec
-
This PR adds a bounded polling helper, but the visualization callbacks that cause the worker-occupation risk still use their old unbounded loops. Merging does not make that worse, but the stated goal is only reached once those callbacks call the helper. The empty-input guards and connection cleanup look sound.
Security architecture risk: 
Low · up to 4c3ec
-
The change improves connection cleanup and SQL identifier handling without a demonstrated increase in access or privileges. Existing visualization waits remain unbounded, and deployment-specific failure behavior has not been fully established.
Retained concerns
No architecture-level concerns identified.Security review details
-
Security Blast Radius
- inferred — The demonstrated impact is on background visualization work and the application's primary/cache database connections. The inspected paths show no new credential authority or externally callable cache endpoint; deployment-wide and tenant-specific exposure remain unestablished.
Trust Boundaries and Controls
- observed — The inspected callbacks receive repository selections through Dash inputs and pass them to repository-filtered cache operations. Query and table identities come from imported query functions, and repository IDs remain bound SQL values. No new caller-controlled function-name source was demonstrated.
Resilience and Maintainability Implications
- inferred — Explicit connection closure reduces the risk that completed or failed cache operations retain database connections. Atomic failure containment relies on normal psycopg2 transaction behavior when an uncommitted connection closes; deployed pooling behavior and concurrent bookkeeping constraints were not verified.
Hardening Proposals
- proposed — If production worker containment is the goal, adopt bounded waiting in the existing callbacks and pair loop deadlines with database-operation timeouts. This would address a pre-existing exposure, not a demonstrated regression introduced here.
-
Pre-merge checks: 
4 · 
1
-
Failed checks: 1 warning Passed checks: 4 passed-
Full details: Description check
-
Explanation
The description provides a detailed summary of the changes, motivation, affected behavior, tests, and linked issue. It does not use the exact template headings or include the required Generative AI disclosure, but the core change information is complete.
Full details: Docstring Coverage
-
Explanation
Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 5 functions across 2 files. (1 skipped: 1 unsupported.)
-
Full details: Linked Issues check
-
Explanation
Issue
#1218requires guards for empty or None repository lists, explicit connection closure, safe table-identifier quoting, and bounded polling for visualization callbacks. The diff implements the cache-facade guards,try...finallyconnection closure,pg_sql.Identifier, andwait_for_cache. However,8Knot/pages/contributions/visualizations/commits_over_time.pystill uses an unboundedwhile not_cached := cf.get_uncached(...)loop withtime.sleep(0.5). The bounded helper is not applied to all affected callbacks.Resolution
Replace the remaining visualization callback polling loops with
cf.wait_for_cache(...), or otherwise apply the same deadline behavior to every affected callback. Add tests that verify callback polling is bounded.
-
Finishing Touches
-
Generate unit tests (beta)
-
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
…ait_for_cache across all visualization callbacks Signed-off-by: Shiva Sharma <shivaumj@gmail.com>
|
hey @EngCaioFonseca can you take a look at this PR! |
Summary of Changes
Closes #1218
This PR addresses critical failure modes in the cache layer and visualization workers:
Guard empty and
Nonerepolistqueries:get_uncached,retrieve_from_cache, andcaching_wrappernow checkif not repolistand short-circuit immediately with empty results ([]orpd.DataFrame()).psycopg2.errors.SyntaxError: syntax error at or near ")"caused byWHERE repo_id IN ()when a user clears repository selection or callbacks trigger prior to repo ID population.TypeError: 'NoneType' object is not iterablewhenNoneis passed.Database connection lifecycle cleanup:
try...finally: conn.close()acrosscache_query_results,get_uncached, andretrieve_from_cache.psycopg2,with pg.connect(...) as conn:only manages transactions (commit/rollback) and does not close the underlying connection upon exit, contributing to database connection exhaustion (Ensure 8Knot doesnt leak connections when materialized views not present #1170).Safe SQL table identifier escaping:
psycopg2.sql.Identifier(tablename)inretrieve_from_cacherather than raw Python string.format().Centralized bounded polling helper:
wait_for_cache(func_name, repolist, timeout=60, caller="")with deadline enforcement and exponential backoff (0.5s → 1.0s → 2.0s up to 5.0s) to provide a standardized, bounded polling utility for visualization callbacks.Unit test suite:
tests/test_cache_facade.pycovering all edge cases (empty lists,None, connection closing, identifier escaping, timeouts, and early returns) with all 8 tests passing.cc @EngCaioFonseca @cdolfi @MoralCode
Would appreciate your review on this PR! It resolves unhandled database syntax crashes and Celery worker thread exhaustion when repository selections change or initial queries load.
Summary by CodeRabbit