.claude/skills/ln-651-query-efficiency-auditor/SKILL.md
Query efficiency audit worker (L3). Checks redundant entity fetches, N-UPDATE/DELETE loops, unnecessary resolves, over-fetching, missing bulk operations, wrong caching scope. Returns findings with severity, location, effort, recommendations.
npx skillsauth add cbbkrd-tech/jl-finishes ln-651-query-efficiency-auditorInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Paths: File paths (
shared/,references/,../ln-*) are relative to skills repo root. If not found at CWD, locate this SKILL.md directory and go up one level for repo root.
Specialized worker auditing database query patterns for redundancy, inefficiency, and misuse.
MANDATORY READ: Load shared/references/task_delegation_pattern.md#audit-coordinator--worker-contract for contextStore structure.
Receives contextStore with: tech_stack, best_practices, db_config (database type, ORM settings), codebase_root.
Domain-aware: Supports domain_mode + current_domain.
Parse context from contextStore
Scan codebase for violations
scan_pathCollect findings with severity, location, effort, recommendation
Calculate score using penalty algorithm
Return JSON result to coordinator
What: Same entity fetched from DB twice in a call chain
Detection:
repo.get(id) or session.get(Model, id), then passes id (not object) to function Brepo.get(id) or session.get(Model, id) for the same entityacquire_next_pending() returns job, but _process_job(job_id) re-fetches itDetection patterns (Python/SQLAlchemy):
repo.*get_by_id|session\.get\(|session\.query.*filter.*id in service/handler filesentity_id: int/UUID AND internally does repo.get(entity_id), check if caller already has entity objectexpire_on_commit setting: if False, objects remain valid after commitSeverity:
Recommendation: Pass entity object instead of ID, or remove second fetch when expire_on_commit=False
Effort: S (change signature to accept object instead of ID)
What: Loop of individual UPDATE/DELETE operations instead of single batch query
Detection:
for item in items: await repo.update(item.id, ...) or for item in items: await repo.delete(item.id)for item in items: session.execute(update(Model).where(...))Detection patterns:
for .* in .*: followed by repo\.(update|delete|reset|save|mark_) within 1-3 linesfor .* in .*: followed by session\.execute\(.*update\( within 1-3 linesSeverity:
Recommendation: Replace with single UPDATE ... WHERE id IN (...) or session.execute(update(Model).where(Model.id.in_(ids)))
Effort: M (rewrite query + test)
What: Re-resolving a value from DB when it is already available in the caller's scope
Detection:
profile_id and resolves engine from it, but caller already determined enginelang_code and looks up dialect_id, but caller already has both lang and dialectX_id, does get(X_id), extracts .field, when caller already has fieldSeverity:
Recommendation: Split method into two variants: with_known_value(value, ...) and resolving_value(id, ...); or pass resolved value directly
Effort: S-M (refactor signature, update callers)
What: Loading full ORM model when only few fields are needed
Detection:
session.query(Model) or select(Model) without .options(load_only(...)) for models with >10 columnsSeverity:
Recommendation: Use load_only(), defer(), or raw select(Model.col1, Model.col2) for list queries
Effort: S (add load_only to query)
What: Sequential INSERT/DELETE/UPDATE instead of bulk operations
Detection:
for item in items: session.add(item) instead of session.add_all(items)for item in items: session.delete(item) instead of bulk deleteINSERT per iterationSeverity:
Recommendation: Use session.add_all(), session.execute(insert(Model).values(list_of_dicts)), bulk_save_objects()
Effort: S (replace loop with bulk call)
What: Request-scoped cache for data that rarely changes (should be app-scoped)
Detection:
Depends()) with internal cache (_cache dict, _loaded flag)Detection patterns:
_cache, _loaded, _initialized attributesSeverity:
Recommendation: Move cache to app-scoped service (singleton), add TTL-based invalidation, or use CacheService with configurable TTL
Effort: M (change DI scope, add TTL logic)
MANDATORY READ: Load shared/references/audit_scoring.md for unified scoring formula.
Return JSON to coordinator:
{
"category": "Query Efficiency",
"score": 6,
"total_issues": 8,
"critical": 0,
"high": 3,
"medium": 4,
"low": 1,
"findings": [
{
"severity": "HIGH",
"location": "app/infrastructure/messaging/job_processor.py:434",
"issue": "Redundant entity fetch: job re-fetched by ID after acquire_next_pending already returned it",
"principle": "Query Efficiency / DRY Data Access",
"recommendation": "Pass job object to _process_job instead of job_id",
"effort": "S"
}
]
}
expire_on_commit, autoflush, session scope before flagging redundant fetchesshared/references/audit_scoring.mdshared/references/audit_output_schema.mdVersion: 1.0.0 Last Updated: 2026-02-04
testing
When the user wants to plan a content strategy, decide what content to create, or figure out what topics to cover. Also use when the user mentions "content strategy," "what should I write about," "content ideas," "blog strategy," "topic clusters," or "content planning." For writing individual pieces, see copywriting. For SEO-specific audits, see seo-audit.
development
When the user wants to create competitor comparison or alternative pages for SEO and sales enablement. Also use when the user mentions 'alternative page,' 'vs page,' 'competitor comparison,' 'comparison page,' '[Product] vs [Product],' '[Product] alternative,' or 'competitive landing pages.' Covers four formats: singular alternative, plural alternatives, you vs competitor, and competitor vs competitor. Emphasizes deep research, modular content architecture, and varied section types beyond feature tables.
development
Write B2B cold emails and follow-up sequences that get replies. Use when the user wants to write cold outreach emails, prospecting emails, cold email campaigns, sales development emails, or SDR emails. Covers subject lines, opening lines, body copy, CTAs, personalization, and multi-touch follow-up sequences.
development
When the user wants to reduce churn, build cancellation flows, set up save offers, recover failed payments, or implement retention strategies. Also use when the user mentions 'churn,' 'cancel flow,' 'offboarding,' 'save offer,' 'dunning,' 'failed payment recovery,' 'win-back,' 'retention,' 'exit survey,' 'pause subscription,' or 'involuntary churn.' This skill covers voluntary churn (cancel flows, save offers, exit surveys) and involuntary churn (dunning, payment recovery). For post-cancel win-back email sequences, see email-sequence. For in-app upgrade paywalls, see paywall-upgrade-cro.