Skip to content

perf(plisql): optimize package dependency cleanup - #1422

Open
Z95-cmyk wants to merge 2 commits into
IvorySQL:masterfrom
Z95-cmyk:perf-package-dependency-sort
Open

Z95-cmyk wants to merge 2 commits into
IvorySQL:masterfrom
Z95-cmyk:perf-package-dependency-sort

Conversation

@Z95-cmyk

@Z95-cmyk Z95-cmyk commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • replace repeated package-list scans with a hash-indexed dependency graph and stable Kahn traversal
  • collect dependent packages and standalone functions in one graph walk instead of recursively revisiting the graph from every package
  • preserve the previous scan-pass and input ordering, including the existing fallback for cycles and dependencies outside the input list
  • add Oracle-mode regression coverage for layered, independent, and cyclic package dependencies
  • include an executable SQL benchmark for the old algorithm’s worst-case dependency order

This PR is now performance-only. The pre-existing cache correctness issue identified during review was split into #1453 with its own regression test and issue.

Performance background

I did not encounter this in a production deployment, so I do not want to imply a real-world incident. Source inspection showed that the previous cleanup repeatedly scanned the remaining package list, making reverse-ordered dependency chains quadratic. The benchmark is an explicitly synthetic worst case intended to make the complexity and scaling reproducible; ordinary installations with fewer cached packages or shallower dependency graphs will see a smaller effect.

The reproducer is committed at src/oracle_test/modules/test_package_reset/benchmark_discard_package_chain.sql. Run it from an IvorySQL psql client against the base and patched revisions, for example:

psql -X -v ON_ERROR_STOP=1 -v package_count=1600 \
  -f src/oracle_test/modules/test_package_reset/benchmark_discard_package_chain.sql DATABASE

Only DISCARD PACKAGE is timed. Package bodies are created in reverse order and each body depends on its predecessor.

Packages Before After
3,200 8,040.366 ms 16.647 ms
6,400 not run 36.427 ms

The 3,200-package synthetic case is about 483x faster, while the patched 3,200-to-6,400 result is close to linear scaling.

Verification

  • make -C src/oracle_test/modules/test_package_reset oracle-check NO_TEMP_INSTALL=1 — 5/5 passed
  • compared the new and old ordering algorithms on 360,000 randomized dependency graphs; all orders matched
  • executed the committed benchmark with package_count=10 after the split to verify that the reproducer runs end to end
  • git diff --check

Fixes #1426

AI assistance disclosure

This contribution was prepared with OpenAI Codex using GPT-5. The agent assisted with source and test inspection, issue scoping, drafting code and tests, running verification, benchmarking, and preparing the PR description. I directed the scope, reviewed the resulting changes against the source and test results, and remain responsible for the submission.

Build and traverse the package dependency graph once while preserving the previous stable cleanup order. Refresh cached package function expressions after dependent function invalidation so DISCARD PACKAGE cannot retain freed package pointers.

Assisted-by: OpenAI:Codex
@coderabbitai

coderabbitai Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

PL/iSQL package cleanup now uses hash-backed dependency traversal and stable topological sorting. Regression coverage validates layered, independent, and cyclic DISCARD PACKAGE behavior, while a generated dependency-chain benchmark measures cleanup time.

Package dependency cleanup

Layer / File(s) Summary
Dependency graph cleanup
src/pl/plisql/src/pl_package.c
Package sorting and dependent-function discovery use hash tables, graph traversal, stable ordering, and compile-state checks.
Discard dependency regression coverage
src/oracle_test/modules/test_package_reset/Makefile, src/oracle_test/modules/test_package_reset/sql/test_discard_dependencies.sql, src/oracle_test/modules/test_package_reset/expected/test_discard_dependencies.out
Regression execution and expected results cover layered, independent, and cyclic package dependencies across DISCARD PACKAGE.
DISCARD PACKAGE benchmark
src/oracle_test/modules/test_package_reset/benchmark_discard_package_chain.sql
A configurable reverse dependency chain is generated, cached, timed through DISCARD PACKAGE, and dropped afterward.

Estimated code review effort: 4 (Complex) | ~60 minutes

Suggested reviewers: nothimmel, jiaoshuntian

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Matches #1426: it optimizes dependency cleanup, preserves ordering semantics, adds layered/independent/cyclic tests, and includes a reproducible benchmark.
Out of Scope Changes check ✅ Passed The added tests and benchmark are directly tied to package cleanup optimization, with no unrelated feature work evident in the change set.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: optimizing PL/iSQL package dependency cleanup.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@Z95-cmyk
Z95-cmyk marked this pull request as ready for review July 20, 2026 04:47
@hs-liuxh

Copy link
Copy Markdown
Collaborator

Hello! Thanks for the work. Just to confirm — is the main goal of this PR the package-cleanup performance optimization?

A few initial review comments:

  1. Please split out the correctness fixes into a separate, higher-priority PR. This PR bundles several changes that are unrelated to performance — the dependent-function cache invalidation (fn_xmin), the stale-parent_func refresh in plisql_get_subproc_*, and pkgcachelist = NIL. These actually fix a real pre-existing crash. That's a valuable fix and should go in on its own, with a regression test that fails before / passes after — independently of the performance discussion.

  2. About the benchmark: the description measures 3,200 packages arranged in a reverse-ordered dependency chain. That looks like a constructed worst case (the cost comes from the chain + ordering, not the count alone). Could you share the real use case or background where you hit slow DISCARD PACKAGE? Also, could you include the benchmark script so the numbers can be reproduced?

Thanks again!

@Z95-cmyk

Copy link
Copy Markdown
Contributor Author

Thanks for the clear review. Yes, the goal of this PR is now solely the package-cleanup performance optimization. I addressed both points:

  1. I removed the correctness changes from this branch and opened the higher-priority fix separately as fix(plisql): refresh package-dependent caches after discard #1453, linked to DISCARD PACKAGE can crash cached PL/iSQL callers #1452. Its focused regression reproduces the pre-existing failure independently: against the performance-only branch, the first cached standalone call after DISCARD PACKAGE terminates the backend with signal 11; the same test passes with fix(plisql): refresh package-dependent caches after discard #1453.
  2. I committed the reproducer at src/oracle_test/modules/test_package_reset/benchmark_discard_package_chain.sql and updated this PR description with the exact command and methodology. I did not encounter this in production; it is an explicitly synthetic worst case discovered through source inspection, designed to expose the old repeated-scan complexity. The description now states that limitation rather than implying a production workload.

After the split, the package-reset module passes 5/5 tests, and the committed benchmark also runs end to end.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/pl/plisql/src/pl_package.c (1)

2582-2584: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

Dead assignment defeats the parent_func refresh.

pfunc = &psource->source; on Line 2582 is immediately clobbered by pfunc = (PLiSQL_function *) funcexpr->parent_func; on Line 2584, so the first assignment has no effect. psource here comes from a fresh PackageCacheLookup, i.e. it's the up-to-date pointer, while funcexpr->parent_func is the value cached on the FuncExpr at an earlier compile — potentially stale/dangling after a DISCARD PACKAGE + recompile cycle. As written, the function unconditionally discards the fresh value and falls back to the (possibly stale) cached one. Per the PR discussion, this class of fix ("stale parent_func refreshes") was flagged as an out-of-scope correctness change that should move to its own PR with a dedicated before/after regression test — this specific instance looks incomplete/ineffective as committed and should be re-examined there.

🐛 Likely intended fix (subject to confirming the actual staleness contract)
-	pfunc = &psource->source;
-
-	pfunc = (PLiSQL_function *) funcexpr->parent_func;
+	/* funcexpr->parent_func may be stale after a DISCARD PACKAGE + recompile;
+	 * refresh it from the freshly-looked-up package source. */
+	pfunc = &psource->source;
+	funcexpr->parent_func = (Node *) pfunc;
🤖 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/pl/plisql/src/pl_package.c` around lines 2582 - 2584, Remove the dead
assignment to pfunc in the surrounding package function refresh logic, or
complete the intended stale parent_func refresh consistently: use the fresh
&psource->source value from PackageCacheLookup rather than immediately
overwriting it with funcexpr->parent_func. Keep this correctness change scoped
to a dedicated follow-up with regression coverage if that behavior is not part
of this PR.
🧹 Nitpick comments (1)
src/pl/plisql/src/pl_package.c (1)

572-791: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add an order-sensitive assertion for the cyclic discard case. The current src/oracle_test/modules/test_package_reset/sql/test_discard_dependencies.sql coverage only checks that DISCARD PACKAGE succeeds; it doesn’t pin the fallback ordering for cyclic or external-dependency packages.

🤖 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/pl/plisql/src/pl_package.c` around lines 572 - 791, Add an
order-sensitive assertion in test_discard_dependencies.sql for the
cyclic/external-dependency discard scenario, verifying the packages are
discarded in the expected fallback order while preserving the existing success
check.
🤖 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.

Outside diff comments:
In `@src/pl/plisql/src/pl_package.c`:
- Around line 2582-2584: Remove the dead assignment to pfunc in the surrounding
package function refresh logic, or complete the intended stale parent_func
refresh consistently: use the fresh &psource->source value from
PackageCacheLookup rather than immediately overwriting it with
funcexpr->parent_func. Keep this correctness change scoped to a dedicated
follow-up with regression coverage if that behavior is not part of this PR.

---

Nitpick comments:
In `@src/pl/plisql/src/pl_package.c`:
- Around line 572-791: Add an order-sensitive assertion in
test_discard_dependencies.sql for the cyclic/external-dependency discard
scenario, verifying the packages are discarded in the expected fallback order
while preserving the existing success check.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d7471fee-364e-45c7-bc97-b6ebee21d45d

📥 Commits

Reviewing files that changed from the base of the PR and between 555a4f1 and db13b90.

📒 Files selected for processing (4)
  • src/oracle_test/modules/test_package_reset/benchmark_discard_package_chain.sql
  • src/oracle_test/modules/test_package_reset/expected/test_discard_dependencies.out
  • src/oracle_test/modules/test_package_reset/sql/test_discard_dependencies.sql
  • src/pl/plisql/src/pl_package.c
💤 Files with no reviewable changes (2)
  • src/oracle_test/modules/test_package_reset/expected/test_discard_dependencies.out
  • src/oracle_test/modules/test_package_reset/sql/test_discard_dependencies.sql

@Z95-cmyk

Copy link
Copy Markdown
Contributor Author

Follow-up on the latest automated review:

  • The reported stale parent_func assignment is valid, but it is intentionally no longer part of this performance diff. It is fixed in the dedicated correctness PR fix(plisql): refresh package-dependent caches after discard #1453 by refreshing package-backed FuncExpr metadata against the current package cache entry before dereferencing it. That PR includes the independent fail-before/pass-after regression requested by the maintainer. Keeping it there avoids reintroducing correctness work into this PR.
  • I did not add a SQL assertion for the internal fallback order because DISCARD PACKAGE exposes no stable per-package release-order result at SQL level; adding debug output solely for a regression would change production behavior. The committed cyclic test exercises successful cleanup/rebuild, while exact ordering was checked separately by comparing the old and new algorithms over 360,000 randomized dependency graphs, including cycles and dependencies outside the input list. All generated orders matched.

So no code change is needed in this performance branch for those two observations.

@hs-liuxh hs-liuxh self-assigned this Aug 3, 2026
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.

Optimize PL/iSQL package dependency cleanup

2 participants