Skip to content

[CBRD-26719] Improve hash join probe phase with parallel execution support - #7068

Merged
youngjinj merged 45 commits into
CUBRID:developfrom
youngjinj:CBRD-26719
May 26, 2026
Merged

youngjinj merged 45 commits into
CUBRID:developfrom
youngjinj:CBRD-26719

Conversation

@youngjinj

@youngjinj youngjinj commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

http://jira.cubrid.org/browse/CBRD-26719

Purpose

Single-context hash join 의 probe 단계를 N 개 워커로 병렬 처리한다. Build 를 마친 primary 가 hash table 을 보유하고, N 개의 secondary context 가 같은 hash table 을 공유하면서 probe 입력 페이지를 섹터 단위로 나눠 처리한다.

Implementation

Parallel probe 진입 조건

  • 파티션이 만들어지지 않는 single-context 경로에서만 시도한다. probe 측 페이지 수와 요청된 병렬도로 환산한 degree 가 2 이상이고 워커 풀 예약이 성공해야 진입한다. 셋 중 하나라도 실패하면 기존 단일 스레드 probe 로 자연스럽게 fallback 한다.

동작 — 빌드 1회, probe 만 N 워커가 분담

  • Build 는 기존대로 단일 스레드로 수행한다. 완성된 read-only 해시 테이블을 N 개 워커가 그대로 공유한다 (워커별 복제 없음).
  • probe 측 입력 페이지는 섹터 단위 atomic claim 으로 워커들이 나눠 가져간다.
  • 각 워커는 자기 출력 list 에 매칭 결과를 emit 한다. 중간 자원 (스캔 / 페이지 fix) 의 open/close 는 모두 같은 워커 스레드 안에서 짝지어 처리한다.

결과 병합 — partition 기반 parallel hash join 과 동일 패턴

  • 모든 워커가 끝나면 메인 스레드가 워커별 출력 list 를 primary 로 직렬 merge 한다. partition 기반 parallel (partition 별 결과 → primary merge) 과 같은 모델이고, primary 에 대한 단일 writer 를 보장한다.

비대상 — 한쪽 입력이 비어 NULL-fill 만 하는 경로

  • 한쪽 입력이 비어있는 OUTER join 의 NULL-fill 경로는 매칭 자체가 없어 hash join 의 build/probe 단계를 거치지 않고 별도 단일 스레드 함수로 처리되므로, parallel probe 의 적용 대상이 아니다.

SQL trace 출력

  • parallel probe 가 활성화된 실행에서는 PROBE 라인 아래에 워커별 시간 / 읽은 행 / 매칭 행 분포 (min..max) 가 서브라인으로 추가된다.
  • 기존 partition 기반 parallel 과는 trace 의 status 값으로 구분되어 두 모드의 통계가 섞이지 않는다.

호출 흐름:

qexec_hash_join
  +-- hjoin_execute
        +-- hjoin_execute_internal
              +-- hjoin_init_context                    # role + parallel promote
              |     +-- hjoin_try_parallel_probe        # if eligible
              |           +-- status = PARALLEL_PROBE
              +-- hjoin_scan_init                       # primary hash_table
              +-- hjoin_build                           # primary only
              |
              +-- hjoin_probe             (dispatcher)
              |     |
              |     +-- [single-thread] hjoin_inner_probe / hjoin_outer_probe
              |     |
              |     +-- [PARALLEL_PROBE]  parallel_query::hash_join::
              |           +-- probe_prepare                    # alloc contexts[N], loop init_contexts:
              |           |                                    # set fill_record by join_type,
              |           |                                    # borrow primary hash_table,
              |           |                                    # open per-context output list_id
              |           +-- probe_execute
              |                 +-- qfile_open_list_sector_scan # probe-side sector layout
              |                 |                               # (membuf CAS + bitmap)
              |                 +-- spawn N workers, then join
              |                 |     +-- probe_task::execute (worker #0..N-1)
              |                 |            (per worker on same thread:
              |                 |             - assert outer/inner list_scan == S_CLOSED
              |                 |             - qfile_open_list_scan(outer/inner)
              |                 |             - sector_page_iterator walk
              |                 |             - close per-worker output list_id
              |                 |             - qfile_close_scan, hjoin_scan_clear)
              |                 +-- for ctx in contexts[N]: hjoin_merge_qlist
              |                 |       (per-worker output list_id → primary)
              |                 +-- qfile_close_list_sector_scan
              |
              +-- hjoin_clear_manager
                    +-- single_context: list_id close/destroy, hjoin_destroy_qlist
                    +-- [PARALLEL_PROBE branch] for each context in contexts[N]:
                    |     +-- parallel_query::hash_join::clear_context
                    |                                   # context list_id close/destroy,
                    |                                   # invariant assert: list_scan
                    |                                   # already closed by probe_task,
                    |                                   # hash_scan == NOT_USE
                    +-- primary single_context: hjoin_scan_clear  # free hash_table

Remarks

  • Secondary 의 shared hash_table 은 hjoin_scan_clear 호출 전 포인터를 명시적으로 NULL 로 unlink 한다 (이중 해제 방지).

Parallelize the single-context hash join probe phase across N workers that share the primary's read-only hash table and split probe-side pages via sector-based atomic claim, with per-worker outputs merged serially into the primary.

…model

Redesign parallel probe so each worker owns an independent HASHJOIN_CONTEXT
while borrowing the hash_table from the primary context. Covers SINGLE /
IN_MEM / HYBRID / HASH_FILE paths and preserves outer-join semantics
(NULL-fill and during_join_pred residuals).

- query_hash_join.[ch]: add hjoin_init/clear_probe_secondary_context helpers,
  extend hjoin_scan_clear with is_shared flag, gate hjoin_try_parallel_probe
  to the single-context path, mirror HASHJOIN_STATUS in stats_group for
  dump classification.
- px_hash_join.cpp: allocate manager->contexts[N] for probe parallelism,
  merge per-worker output list_ids into the primary context.
- px_hash_join_task_manager.[ch]pp: split probe_task::execute into
  execute_inner / execute_outer dispatched by join type; borrow per-worker
  TLS clones via spawn_manager for outer residual predicates.
- query_dump.c: use stats_group->status to distinguish PARTITION vs
  PARALLEL_PROBE when context_cnt > 1.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown

🧪 TC Test Environment Ready

CircleCI Testing:

  • CircleCI will automatically test using the branches below.

TC Repositories & Branches:

Next Steps:

  1. Wait for CircleCI tests to complete
  2. If CircleCI tests failed, please check the test results and fix the issues.
  3. When ready to merge this PR, please merge the TC PR first, then merge this PR.

youngjinj and others added 13 commits April 20, 2026 19:14
Text and partition-JSON dump paths already emit probe.time as "min..max"
ms when num_parallel_threads > 1; the single-context JSON path was still
unconditionally writing elapsed_time, losing the per-worker range view
under PARALLEL_PROBE.

Also promote stats_group->status to a local for readability in both
text and JSON dump helpers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…is_shared

Move hjoin_try_parallel_probe into hjoin_init_context so the parallel
promotion is decided alongside build/probe role assignment. The caller
now branches on context->status (PARALLEL_PROBE vs others), removing
the duplicated #ifdef block that previously lived in
hjoin_execute_internal. qfile_open_list for the serial output list is
deferred into the serial branch so the parallel path skips that
allocation entirely.

Rename parallel_query::hash_join::probe_partitions to probe_execute;
probe_task::execute already dispatches inner vs outer internally, so a
single coordinator entry point matches the actual split.

Replace the HASHJOIN_CONTEXT::hash_table_is_shared flag and the
is_shared parameter on hjoin_scan_clear with an explicit unlink in
hjoin_clear_probe_secondary_context: secondary contexts null the
borrowed hash_table pointer before hjoin_scan_clear, and
hjoin_scan_clear's destroy path (already NULL-guarded) skips the
primary-owned table naturally.

Also drop the redundant HASHJOIN_STATUS_ERROR check immediately after
hjoin_try_parallel in hjoin_try_partition; the following switch already
routes ERROR to error_exit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…::hash_join

Rename hjoin_init_probe_secondary_context / hjoin_clear_probe_secondary_context
to parallel_query::hash_join::probe_init_contexts / probe_clear_contexts and
relocate their bodies next to probe_prepare / probe_execute. The parallel-probe
specific helpers now live alongside the rest of the namespace, keeping
query_hash_join.c focused on the serial/partition paths.

hjoin_scan_clear is promoted from a static helper to a header-declared symbol so
the relocated clear routine can still invoke it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Inline the temp_key / temp_new_key frees inside probe_clear_contexts instead of
reaching back into query_hash_join.c. The hash_table is already nulled just
above, so hjoin_scan_clear would only have done those two qdata_free_hscan_key
calls anyway. With no cross-TU caller left, hjoin_scan_clear goes back to file
scope.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Move probe_prepare / probe_execute before probe_init_contexts / probe_clear_contexts
in px_hash_join.cpp so the definition order mirrors the header declarations.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…hjoin_clear_manager

Move HASHJOIN_PRINT_STEP enum and HJOIN_PRINT_TUPLE macro from query_hash_join.c
into query_hash_join.h so parallel-probe workers can emit the same print-step
tokens from px_hash_join_task_manager.cpp.

hjoin_clear_manager's HASHJOIN_STATUS_PARALLEL_PROBE branch now tears down the
secondary contexts inline (close scans, free temp keys, drop borrowed pointers,
destroy leftover per-worker list_id) instead of delegating to a separate
parallel_query::hash_join::probe_clear_contexts helper. The helper becomes
unnecessary once cleanup lives where the rest of context teardown lives.

hjoin_execute_internal opens the probe-side list_scan_id only on the serial
path; PARALLEL_PROBE workers open their own scans.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…pers

Fold probe_prepare_contexts's single-secondary init logic directly into
probe_prepare, and drop probe_clear_contexts altogether (teardown now lives in
hjoin_clear_manager's PARALLEL_PROBE branch).

probe_prepare now also opens the per-worker output list_id, picks up
fill_record / need_coerce_type from the primary, and, when tracing is active,
allocates the per-context HASHJOIN_STATS array used by trace dump.

Drop the namespace function declarations for the removed helpers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…spawn_manager

task_execution_guard gets a new get_spawn_manager() helper that lazily obtains
the per-worker TLS, and its destructor now calls spawn_manager::destroy_instance
so every task (split/join/probe) shares one teardown point. join_task and
probe_task drop their explicit destroy_instance() cleanup and go through the
new guard helper.

base_task's constructor absorbs the assert (m_manager->context_cnt > 1); join
and probe constructors drop the now-redundant checks.

probe_task::execute opens the per-worker output list_id and outer/inner
list_scan_ids up front, hands the context to execute_outer / execute_inner,
and cleans up the output list only on error.

execute_outer and execute_inner stop duplicating the TLS / px_stats setup
(execute() already handled it) and now assume m_context is fully primed when
called. execute_inner is rewritten to the serial hjoin_probe shape - using
m_context->{outer,inner,build,probe} / hash_scan directly - so profiling
macros fire in the same places as the serial path.

Fix a latent page-buffer leak in split_task::execute and the rewritten
execute_inner: when QFILE_GET_TUPLE_COUNT returns 0, the empty page needs
qmgr_free_old_page_and_init before 'continue', otherwise the reference is
overwritten on the next iteration.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…obe_end

Refactor N-context parallel probe to own per-worker lifecycle cleanly:

- Split probe_prepare into init_contexts (per-context setup) + probe_prepare
  (array alloc + stats setup loop) + probe_end (teardown closing scans and
  nulling borrowed hash_table via HASH_METH_NOT_USE).
- Add clear_context helper; route hjoin_clear_manager PARALLEL_PROBE branch
  through it so borrowed primary hash_table is never double-freed even on
  error paths that skip probe_end.
- Consolidate hjoin_probe into a dispatcher: PARALLEL_PROBE calls
  probe_prepare/execute/end, non-parallel path calls hjoin_inner_probe
  (renamed from hjoin_probe) or hjoin_outer_probe.
- Expose hjoin_scan_init/hjoin_scan_clear via query_hash_join.h and let
  hjoin_scan_init accept NULL list_id to skip hash-table creation, which
  init_contexts uses since secondaries borrow the primary table.
- Set build-side list_scan_id.is_read_only once in init_contexts instead of
  per-iteration inside execute_inner.
- Simplify probe_task::execute: acquire spawn_manager up front, set/clear
  TLS once, drop the do/while(false) control-flow trick, and let
  task_execution_guard own spawn_manager teardown.
- Fix empty-page buffer leak in execute_inner (qmgr_free_old_page_and_init
  before continue).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Align probe_task::execute_outer with execute_inner so both task paths share
the same page-walk scaffolding (shared probe page claim, profile macros,
m_context->list_id output, m_context->stats accounting):

- Match definition order to header declaration: execute, execute_inner,
  execute_outer, get_next_page.
- Use m_context->list_id (pre-opened by init_contexts) instead of opening a
  per-task local_list_id inside execute_outer.
- Drop the probe_is_outer slot-swap logic; use outer->fill_record /
  inner->fill_record directly, matching serial hjoin_outer_probe.
- Preserve outer-join branches (null-key emit, any_record_added, during_join_pred
  evaluation with HJOIN_PROFILE_PROBE_MATCH timing, no-match fill emit) and
  HJOIN_PRINT_TUPLE trace markers.
- Tidy include blocks: shorten listed symbols to 2-3 representative names
  plus \"...\", alphabetise order, and add missing storage_common.h to
  task_manager.cpp (for PAGE_PTR, VPID_*, S_CLOSED). Drop redundant
  query_hash_join.h / query_hash_scan.h from px_hash_join.cpp since they
  come via px_hash_join.hpp.
- Move hjoin_update_tuple_hash_key declaration above hjoin_probe_key in
  query_hash_join.h for grouping.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…t.list_id

hjoin_merge_qlist can leave single_context.list_id == NULL when it fails
midway (e.g. qfile_combine_two_list allocation failure on the first merge
iteration). HJOIN_PROFILE_MERGE_END fires before the error check, so
dereferencing list_id unconditionally would crash when the profile macro is
active. Pass 0 as the merged tuple count in that case.

Also fix a missing space in the error_manager.h include comment.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The parallel_query layer is already guarded by SERVER_MODE across the
project, and the WINDOWS exclusion dates from earlier parallel-probe
scaffolding that is no longer relevant. Use SERVER_MODE alone for the
parallel_probe branches in hjoin_try_partition, hjoin_init_context,
hjoin_probe, and hjoin_clear_manager so the conditional compilation is
consistent with the rest of the parallel code paths.

Also inline the probe list-id access in hjoin_try_parallel_probe (drop the
probe_list_id / page_cnt temporaries) and wrap the NULL-guarded list_id
dereference in hjoin_execute_partitions to match astyle formatting.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@github-actions

github-actions Bot commented Apr 23, 2026 •

Copy link
Copy Markdown

✅ TC Merge Gate — Merge Allowed

All TC PRs are merged, closed, or not present.

TC Repositories & Branches:

  • ✅ cubrid-testcases: No open TC PR (merged, closed, or not created)
  • ✅ cubrid-testcases-private-ex: No open TC PR (merged, closed, or not created)

…lel_probe

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@youngjinj

Copy link
Copy Markdown
Contributor Author

/run sql medium

…s assert

Ensure each probe_task closes its per-worker list_id at the cleanup label so
qfile scan state is released even on the error exit path, and remove an
obsolete HASHJOIN_STATUS_TRY assertion in hjoin_probe that no longer holds
when parallel probe dispatches through the same entry point.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@youngjinj

Copy link
Copy Markdown
Contributor Author

/run sql medium

youngjinj and others added 2 commits April 24, 2026 02:00
Expose parallel-probe spread in trace: emit a sub-line under PROBE with
workers, time/readrows/readkeys/rows min..max, and move parallel-workers
out of the HASHJOIN header when probe is parallel. Skip the misleading
sum of build/probe elapsed_time across contexts for parallel paths.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Reuse hjoin_scan_clear at end of probe_task::execute so that the
coerce buffer allocated by qstr_coerce (string_opfunc.c:9538) for
temp_key / temp_new_key is released within the task scope, keeping
the per-task resource tracker balanced and avoiding stale buffers
that could later be freed by a different path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@youngjinj

Copy link
Copy Markdown
Contributor Author

/run sql medium

youngjinj and others added 2 commits April 24, 2026 15:55
…h style

Move the per-context hjoin_scan_init and hash-table sharing out of
init_contexts into probe_task::execute so that init_contexts leaves
hash_list_scan_type at HASH_METH_NOT_USE until the task runs. Replace
the C++17 [[fallthrough]] attribute with a /* fall through */ comment
for consistency with the rest of the file.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
qdump_print_hashjoin_stats_text/_json aborted when stats_group had
per-context stats while running the HASHJOIN_STATUS_PARALLEL_PROBE
path in trace mode. Extend the invariant to accept that status so
the existing single-stats layout branch can render the plan.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@youngjinj

Copy link
Copy Markdown
Contributor Author

/run all

youngjinj and others added 2 commits April 27, 2026 13:18
Open build/probe list_scan inside probe_task::execute and close them on
the same worker thread so pgbuf fix/unfix pair within the same
resource_tracker; the previous parent-thread cleanup tripped
restrack_assert because read_only LATCH_READ fixes leaked across threads.
Add invariant asserts on entry and in clear_context, and drop the
now-redundant probe_end function.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Resolve conflicts in src/query/parallel/px_hash_join/{px_hash_join.cpp,
px_hash_join_task_manager.cpp}: keep CBRD-26719 parallel-probe context
lifecycle while integrating CBRD-26666 sector-based split-phase page
distribution (membuf CAS claim + per-sector bitmap iteration, switch
to m_current_tfile for overflow/free unfix, qfile_truncate_list, and
hjoin_trace_merge_stats status arg).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@greptile-apps

greptile-apps Bot commented May 19, 2026

Copy link
Copy Markdown
Contributor

Reviews (7): Last reviewed commit: "[CBRD-26719] Factor out overflow tuple r..." | Re-trigger Greptile

…low_tuple

The overflow VPID-chain walk used by qfile_get_tuple was duplicated three
times in the parallel hash join workers (split_task and probe_task's inner /
outer paths). Factor it into a single qfile_assemble_overflow_tuple helper in
list_file.c that takes the tfile explicitly, since dependent_list_id chains
in the parallel scan can hand back pages from different tfiles than
list_id->tfile_vfid.

qfile_get_tuple now delegates its overflow branch to the helper and keeps
the in-page memcpy path unchanged. The parallel hash join callers drop the
inline copies and call qfile_assemble_overflow_tuple directly with the
sector_page_iterator's current tfile, then redirect tuple_record.tpl to the
reassembled buffer.

Also tidy qfile_get_tuple's parameter names to spell out source / destination
roles (src_tuple, dest_tplrec, first_page_p, list_id_p) and rewrite both
function doc comments in the descriptive style used elsewhere in list_file.c.
@youngjinj

Copy link
Copy Markdown
Contributor Author

/run all

@greptile-apps

greptile-apps Bot commented May 19, 2026

Copy link
Copy Markdown
Contributor

Reviews (8): Last reviewed commit: "[CBRD-26719] Move overflow tuple reassem..." | Re-trigger Greptile

…oc comments

Wrap the description text under the function signature so continuation lines
align under the first character after "() -", and break the long sentence in
qfile_assemble_overflow_tuple's comment at natural clause boundaries instead
of relying on the previous 3-space indent.
@greptile-apps

greptile-apps Bot commented May 19, 2026

Copy link
Copy Markdown
Contributor

Reviews (9): Last reviewed commit: "[CBRD-26719] Reflow qfile_get_tuple / qf..." | Re-trigger Greptile

@greptile-apps

greptile-apps Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

Reviews (10): Last reviewed commit: "[CBRD-26719] Rename init_contexts to ini..." | Re-trigger Greptile

@greptile-apps

greptile-apps Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

Reviews (11): Last reviewed commit: "[CBRD-26719] Rename init_contexts to ini..." | Re-trigger Greptile

The parallel probe_task drives the probe input via sector_page_iterator,
so probe->list_scan_id is opened and closed but never iterated. Remove
the redundant qfile_open_list_scan / qfile_close_scan pair and the now-
stale outer/inner scan precondition asserts; keep an assert on
build->list_scan_id, which hjoin_probe_key actually consumes.

To match, switch HJOIN_PRINT_TUPLE and hjoin_print_tuple to accept a
QFILE_LIST_ID * directly. Only tuple_cnt and type_list were ever read
from the prior QFILE_LIST_SCAN_ID *, so the new signature is
functionally identical and lets the parallel path emit dump trace
without an open scan on the probe side.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@greptile-apps

greptile-apps Bot commented May 22, 2026

Copy link
Copy Markdown
Contributor

Reviews (12): Last reviewed commit: "[CBRD-26719] Drop unused probe list_scan..." | Re-trigger Greptile

@youngjinj

Copy link
Copy Markdown
Contributor Author

/run all

@greptile-apps

greptile-apps Bot commented May 22, 2026

Copy link
Copy Markdown
Contributor

Reviews (13): Last reviewed commit: "Merge remote-tracking branch 'upstream/d..." | Re-trigger Greptile

youngjinj pushed a commit to CUBRID/cubrid-testcases that referenced this pull request May 26, 2026
http://jira.cubrid.org/browse/CBRD-26719

Update answers for 4 SQL tests affected by the parallel-probe trace subline, and pin cbrd_25382 hash join queries with `NO_PARALLEL_HASH_JOIN` to keep the trace deterministic for non-parallel-probe coverage.
@youngjinj
youngjinj merged commit 86c249d into CUBRID:develop May 26, 2026
13 of 14 checks passed
@github-actions

Copy link
Copy Markdown

✅ TC Branch Finalized for cubrid-testcases-private-ex

Engine PR was merged.

Cleanup Results:

  • Branch tc/pr-7068: Deleted

TC base branch is ready for the next PR.

@github-actions

Copy link
Copy Markdown

✅ TC Branch Finalized for cubrid-testcases

Engine PR was merged.

Cleanup Results:

  • Branch tc/pr-7068: Deleted

TC base branch is ready for the next PR.

hyunikn added a commit to hyunikn/cubrid that referenced this pull request May 26, 2026
hyunikn added a commit to hyunikn/cubrid that referenced this pull request May 26, 2026
hyahong added a commit that referenced this pull request Jun 18, 2026
* [CUBRIDQA-1320] Add TC merge gate workflow to block engine PR merge until TC PRs are merged or closed (#7019)

* [CUBRIDQA-1320] Add TC merge gate workflow to block engine PR merge until TC PRs are merged or closed

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* [CUBRIDQA-1320] Optimize tc-merge-gate workflow

- Remove redundant token masking step (create-github-app-token masks automatically)
- Add --limit 1 to gh pr list to minimize API response
- Wrap comment posting in best-effort block (comment failure no longer affects check result)
- Fix heredoc indentation to prevent YAML parse errors

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Update .github/workflows/tc-merge-gate.yml

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update .github/workflows/tc-merge-gate.yml

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* [CBRD-26711] Support avg,sum function on parallel heap scan (#7049)

http://jira.cubrid.org/browse/CBRD-26711

Purpose
To improve the performance of BUILDVALUE_PROC (single tuple aggregation without GROUP BY) queries in CUBRID's parallel heap scan feature, the supported aggregate functions are expanded.
In the existing parallel heap scan implementation, only COUNT(*), COUNT(col), and COUNT(DISTINCT col) were supported for optimization (COUNT_DISTINCT) regarding BUILDVALUE_PROC. Consequently, queries containing aggregate functions such as MIN/MAX/SUM/AVG/STDDEV/VARIANCE were executed serially or processed via MERGEABLE_LIST or XASL_SNAPSHOT methods, leading to unnecessary overhead. To resolve this, the COUNT_DISTINCT optimization is expanded to BUILDVALUE_OPT, introducing a mechanism where each worker thread independently performs partial aggregation and efficiently merges the results in the final stage.

Implementation
Expand aggregate function support (px_heap_scan_checker.cpp)

Add the is_buildvalue_opt_supported_function() helper function to determine supported aggregate functions (COUNT_STAR, COUNT, MIN, MAX, SUM, AVG, STDDEV, STDDEV_POP, STDDEV_SAMP, VARIANCE, VAR_POP, VAR_SAMP).

Change the existing condition agg_it->function != PT_COUNT_STAR && agg_it->function != PT_COUNT to !is_buildvalue_opt_supported_function(agg_it->function).

Expand worker thread initialization (px_heap_scan_result_handler.cpp - write_initialize)

COUNT_STAR: Initialize curr_cnt=0

DISTINCT (All types): Open an independent list per thread

Non-DISTINCT (MIN/MAX/SUM/AVG/STDDEV*/VAR*): Initialize curr_cnt=0

Add row-level accumulation logic (px_heap_scan_result_handler.cpp - write)

PT_COUNT: curr_cnt++

PT_MIN: If cmpval > 0, copy after domain conversion

PT_MAX: If cmpval < 0, copy after domain conversion

PT_SUM/PT_AVG: Copy and convert the first row, then accumulate using qdata_add_dbval, curr_cnt++

PT_STDDEV*/PT_VAR*: Convert to double, calculate X^2, accumulate value and value2, curr_cnt++

DISTINCT: Insert into the thread-specific list (same as the existing pattern)

Expand merge logic (px_heap_scan_result_handler.cpp - write_finalize)

COUNT_STAR: orig.curr_cnt += worker.curr_cnt

DISTINCT: Merge lists using qfile_connect_list

Non-DISTINCT COUNT: orig.curr_cnt += worker.curr_cnt

Non-DISTINCT MIN/MAX/SUM/AVG/STDDEV*/VAR*: Switch to heap 0 using db_change_private_heap(thread_p, 0), call qdata_aggregate_accumulator_to_accumulator(), and then restore the original heap. If accumulator_domain is uninterpreted, copy the worker's interpreted domain.

Reallocate main thread values (px_heap_scan_result_handler.cpp - read)

After waiting for workers to complete, reallocate the accumulator values of Non-DISTINCT/Non-COUNT aggregations to the main thread's private heap.

Copy the value allocated in heap 0 to the private heap using pr_clone_value, switch to heap 0, and free the original value using pr_clear_value.

This ensures proper deallocation from the correct heap when pr_clear_value is called in qexec_end_buildvalueblock_iterations.

* [CBRD-26678] Support parallel index build (#7011)

http://jira.cubrid.org/browse/CBRD-26678

Purpose
To add a feature that parallelizes the step of reading and sorting records from a heap file using multiple threads during B+tree index creation (CREATE INDEX / xbtree_load_index). This is implemented by reusing the existing parallel sort (ORDER BY) infrastructure and adding an implementation for an index build-specific type (SORT_INDEX_LEAF).

Implementation
Heap Sector Partitioning

Collect all sectors of the heap file using file_get_all_data_sectors

Distribute evenly among threads using ftab_set::split(parallel_num)

Each thread scans only its allocated sectors (get_next_vpid)

Independent Execution per Thread (sort_listfile_execute, SORT_INDEX_LEAF branch)

btree_load_filter_pred_function_info — Independent deserialization of filter/func index predicates per thread

bt_load_heap_scancache_start_for_attrinfo — Start heap scancache per thread

btree_sort_get_next_parallel — Perform parallel scan by moving pages on a sector basis

Result Merging (sort_merge_run_for_parallel_index_leaf_build)

Tree-merge the result temporary files of each thread by SORT_PX_MERGE_FILES

After all merges are completed, btree_create_file → sort_put_result_from_tmpfile

SERVER_MODE / SA_MODE Branching

SERVER_MODE: Delegate log_sysop_start, btree_create_file, and heap scancache into sort_listfile

SA_MODE: Maintain the existing sequential method

Major Changed Files

btree_load.h / btree_load.c — Moved and expanded the SORT_ARGS structure, added FILTER_INDEX_INFO, and added parallel scan functions

external_sort.c / external_sort.h — Comprehensively added the SORT_INDEX_LEAF branch and added a new parallel merge function

file_manager.c / file_manager.h — Added file_get_num_data_sectors

* [CBRD-26666] Improve parallel hash join split phase with sector-based page distribution (#6981)

Replace `scan_mutex` serialization in the split phase with a lock-free sector-bitmap distribution: workers claim sectors via an atomic counter and walk each 64-page bitmap with `__builtin_ctzll` to compute VPIDs directly, eliminating per-page mutex contention. Adds membuf CAS claim, per-worker `m_current_tfile` tracking for dependent lists, and overflow continuation-page skip.

* [CBRD-26743] [CMS] upgrade certificates to 2048 bits base RSA (#7107)

upgrade certificates to 2048 bits base RSA

* [CBRD-26745] Flush deferred query handlers on net callback error path and cas finalize (#7109)

http://jira.cubrid.org/browse/CBRD-26745

fix CAS crash on deferred query_handler free

- Ensure `callback_handler::free_deferred_query_handler()` runs on all RPC exit paths via RAII guard  
- Add fast-path `has_deferred_query_handler()` to skip unnecessary flush  
- Drain all query handlers at shutdown (`clear_all_query_handlers()` before `ws_final()`)  

Fixes double-free/use-after-free of `DB_SESSION` leading to `mspace_free` abort.

* [CBRD-26718] fix assertion failure in perfmon_add_at_offset() (#7081)

http://jira.cubrid.org/browse/CBRD-26718

 - prevent assertion in perfmon_add_at_offset() by checking for valid transaction indices.
 - This addresses a race condition where a transaction ends before its interrupted state is processed.

* [CBRD-26698] (change build option) bug-fix: correct length when handling shard keys (#7116)

http://jira.cubrid.org/browse/CBRD-26698 (debug build option change)

* [CBRD-26754] An error occurs when executing an update statement containing a db_link. (#7127)

http://jira.cubrid.org/browse/CBRD-26754

* [CBRD-26109] adjust signal restoration position (#7125)

http://jira.cubrid.org/browse/CBRD-26109

* [CBRD-26478] Refactor lock manager initialization (#6930)

http://jira.cubrid.org/browse/CBRD-26478

### Purpose

This change refactors `lock_manager` initialization/finalization to centralize runtime configuration, make lock-manager-owned resources explicit, and make partial-initialization cleanup safe.

- Initialization defaults and derived sizing logic are now managed in one place.
- Resource ownership, initialization state, and cleanup order are clearer.
- Finalization now explicitly tracks which lock-manager substructures were initialized before attempting cleanup.
- The refactor is not intended to change behavior under default settings.

### Implementation

- Consolidated initialization parameters and derived runtime values into an internal lock-manager config (`LK_CONFIG`).
- Replaced scattered globals and hardcoded initialization values with config-backed fields (transaction count, transaction local pool sizing, object lock sizing, deadlock detection sizing, verbose mode, dump level).
- Added a dedicated initialization-state structure (`LK_INIT_STATE`) to track substructure initialization consistently for the transaction lock table, object lock structures, and deadlock detection resources.
- Tracked partial transaction-table initialization using an initialized-entry count so mutex teardown only runs for fully initialized entries.
- Merged object lock hash-table and freelist setup into a single initialization path.
- Split cleanup into dedicated finalization steps for the transaction lock table, object lock structures, and deadlock detection resources.
- Replaced fixed deadlock-related storage with lock-manager-owned dynamic allocations (`TWFG_edge_storage`, `victims`).
- Made deadlock detector cleanup safer by nulling the daemon pointer after destroy and guarding `pthread_mutex_destroy()` with explicit initialization state.
- Kept the existing public test-facing initialization entry points intact while routing them through the internal config-based initialization path.

* [CBRD-26767] Remove unused CI config (.travis.yml) (#7145)

http://jira.cubrid.org/browse/CBRD-26767

* [CBRD-26744] Remove unused length out-parameter from db_get_char() and prune dead intl_char_count usages (#7102)

http://jira.cubrid.org/browse/CBRD-26744

- Drop dead `length` out-param from db_get_char() and update all callers
- Add 8-byte SWAR ASCII fast path in intl_count_utf8_chars/bytes/check_utf8
- Replace intl_nextchar_utf8() with intl_Len_utf8_char[] lookup (same TU)
- Skip intl_char_count() when byte_size <= precision in truncate paths
- Add CAS payload trailing-NUL defensive asserts (debug only)

* [CBRD-26062] Add SIGUSR1-triggered memory dump of logwr_Gl (copylogdb) and la_Info (applylogdb) (#6211)

http://jira.cubrid.org/browse/CBRD-26062

* [CBRD-26640] Reuse correlated DBLink result set via CCI cursor rewind (#7103)

http://jira.cubrid.org/browse/CBRD-26640

* [CBRD-26643] Replace std::string copy in lowercase_hash with FNV-1a (#7133)

http://jira.cubrid.org/browse/CBRD-26643

  - Replace lowercase_hash body with a single-pass FNV-1a 64-bit hash to remove the per-call std::string allocation and the separate lowercase transform pass.
  - Preserve case-insensitive consistency with lowercase_compare via the same tolower fold-in during hashing.
  - Drop the now-unnecessary direct <string> include.

* [CBRD-26739] snapshot cubrid.conf to prevent runtime failures from cubrid.config edits (#7135)

http://jira.cubrid.org/browse/CBRD-26739

Currently, the Broker and CAS refer directly to '$CUBRID/conf/cubrid.conf' during runtime.
This poses a risk where accidental user edits to the configuration file can cause service failures when a CAS restarts.

To isolate the running service from manual configuration changes, this commit implements a snapshot mechanism that clones the configuration at startup.

Changes:
- Broker Startup: Copies 'cubrid.conf' to '$CUBRID/var/as_pid/.cubrid.conf' and registers the 'CUBRID_CONF_FOR_BROKER' environment variable.
- Broker Shutdown: Automatically removes the cloned '.cubrid.conf' file.
- Client/CAS Logic: Updated 'boot_restart_client()' to prioritize the snapped config via 'CUBRID_CONF_FOR_BROKER'.
                    Falls back to the original 'cubrid.conf' if the variable is missing or the file is unreadable.

* [CBRD-26773] Mark stored_procedure params reloadable to avoid false "not running" (#7159)

http://jira.cubrid.org/browse/CBRD-26773

Fix `cubrid pl status` reporting a running `cub_pl` as "not running" when an earlier database in `cubrid.conf` declares `stored_procedure=no` in its `[@<db>]` section.

- Add `PRM_RELOADABLE` to the flag bitmask for the parameter in `src/base/system_parameter.c` so the reset-to-default pass picks them up on reload

* [CBRD-26705] [Regression][isolation] Phantom read occurs at RepeatableRead isolation level (#7063)

http://jira.cubrid.org/browse/CBRD-26705

* [CBRD-26789] fix a wrong null termination of an error message (#7166)

fix a wrong null termination of an error message

* [CBRD-26772] Remove db_password member from BOOT_CLIENT_CREDENTIAL struct (#7155)

http://jira.cubrid.org/browse/CBRD-26772

[refactoring] Remove db_password member from BOOT_CLIENT_CREDENTIAL struct

* [CBRD-26771] Fix stack-buffer-overflow in file_create() (#7154)

http://jira.cubrid.org/browse/CBRD-26771

* Fix stack-buffer-overflow in file_create()

* [CBRD-26768] Fix stack-use-after-scope in do_prepare_select() (#7144)

http://jira.cubrid.org/browse/CBRD-26768

* Fix stack-use-after-scope in do_prepare_select() function.

* [CBRD-26747] Enable fixed scan for outer heap scans in NLJ by default (#7108)

http://jira.cubrid.org/browse/CBRD-26747

Add enable_heap_fixed_scan to enable fixed scan by default for performance; previous logic disabling it for inner index scans is obsolete after pgbuf_ordered_fix.

* [CBRD-26739] move _er_log_debug() call after er_init() (#7172)

http://jira.cubrid.org/browse/CBRD-26739

- relocated the er_log_debug call to occur after er_init to ensure the error logging system is properly initialized before recording any debug messages.

* [CBRD-26291] Recovery for Coordinator (#6820)

http://jira.cubrid.org/browse/CBRD-26291

* [CBRD-25862] [CBRD-26401] [CBRD-25471] [CBRD-26708] [CBRD-26676] system catalog update(invisible column, timestamps...) (#6903)

http://jira.cubrid.org/browse/CBRD-25862
http://jira.cubrid.org/browse/CBRD-26401
http://jira.cubrid.org/browse/CBRD-25471
http://jira.cubrid.org/browse/CBRD-26708
http://jira.cubrid.org/browse/CBRD-26676

Bundle five system-catalog cleanup tickets into a single PR.

- Split db_user / db_password / db_authorization into _db_* base classes with same-named views, and add created_time / updated_time / invalidated_time / expire_time columns (CBRD-25862)
- Introduce INVISIBLE / VISIBLE column keywords and surface the flag information through _db_attribute, applying visibility policy to SELECT *, JOIN, and CREATE TABLE AS SELECT (CBRD-26401)
- Tighten _db_user.name to varchar(32) (DB_MAX_USER_LENGTH) and propagate the change to dependent owner-name view columns (CBRD-25471)
- Activate sql_data_access on _db_stored_procedure and the db_stored_procedure view, and carry the field through the PL/CSQL compile response (CBRD-26708)
- Expose the same flag information on the db_attribute view: add is_partition_key, and extend the default_value column domain to express AUTO_INCREMENT (CBRD-26676)

* [CBRD-26809] Include <string> in identifier_store.hpp for modern toolchains (#7185)

https://jira.cubrid.org/browse/CBRD-26809

* [CBRD-26820] Fix Au_disable leak from parser->au_save overwrite in do_select_internal (#7199)

  http://jira.cubrid.org/browse/CBRD-26821

  - Save/restore the caller's auth-save slot around the inner SELECT helper
    so it no longer leaks Au_disable into the surrounding UPDATE.

* [CBRD-25862] Switch contrib/scripts to _db_user after db_user view split (#7208)

http://jira.cubrid.org/browse/CBRD-25862

Following the db_user modification in PR #6903, update contrib/scripts to depend directly on the base table (_db_user) instead of the view.

- Switch DBA group membership probe and reserved word conflict checks from db_user view to _db_user table.
- Remove `CAST AS VARCHAR(255)` from the owner_name column to align with the narrowed type of _db_user.name (varchar(32)).

* [CBRD-26791] log error in CAS log while handling method callbacks (#7167)

* log error in CAS log while handling method callbacks
  - er_stack_push and er_stack_pop in order not to affect the error id with the error logging
  - log only when not already error logged

* [CBRD-26719] Improve hash join probe phase with parallel execution support (#7068)

http://jira.cubrid.org/browse/CBRD-26719

Parallelize the single-context hash join probe phase across N workers that share the primary's read-only hash table and split probe-side pages via sector-based atomic claim, with per-worker outputs merged serially into the primary.

* [CBRD-25863] Implement Information Schema (#7174)

http://jira.cubrid.org/browse/CBRD-25863
http://jira.cubrid.org/browse/CBRD-26631
http://jira.cubrid.org/browse/CBRD-26612

Introduce the SQL:2003 INFORMATION_SCHEMA into CUBRID as 19 static views,
each applying row-level filtering based on the caller's privilege visibility,
together with the helper SQL functions and privilege-model changes needed to
populate the standard columns.

- CBRD-25863 — INFORMATION_SCHEMA:
  - A dedicated INFORMATION_SCHEMA system user owns every view; it cannot log
    in, be dropped, or have its privileges altered.
  - Hybrid definer/invoker privilege model: system catalogs are DBA-owned and
    grant SELECT only to INFORMATION_SCHEMA; each view is owned by
    INFORMATION_SCHEMA and grants SELECT to PUBLIC.
  - Install runs as an independent step after system catalog installation.
  - View names have a single source of truth that other modules consult.
  - Column order is aligned with PostgreSQL information_schema for tool compatibility.
  - Privilege gating uses a two-tier macro family (atomic conditions composed
    into per-view-type gates).
- CBRD-26631 — COLLECTION_TO_STRING: unary SQL function serializing a
  SET/MULTISET/SEQUENCE to VARCHAR, used by partitions.partition_description.
- CBRD-26612 — estimated_* statistics functions (estimated_table_rows,
  estimated_avg_row_length, estimated_data_length, estimated_data_free) that
  populate the standard table/partition statistics columns.

* [CBRD-26510] [Regression] Core dumped in cubthread::worker_pool<cubthread::entry>::stop_execution at src/thread/thread_worker_pool.hpp:688 (#7191)

http://jira.cubrid.org/browse/CBRD-26510
When the heap_insert_logical() function executes and fails to insert a record into a specific slot on a page for certain reasons, it acquires a write latch but fails to release it.
Subsequently, when the page is flushed (due to checkpoint or server stop), the thread performing the flush determines that another thread is holding the write latch and requests an async flush. This causes the thread to enter an infinite wait state.
To prevent this infinite wait, the following solution is applied:
After goto error handling in the heap_insert_logical() function, call heap_unfix_watchers(thread_p, context) to release the occupied latch.

* [CBRD-26799] Fix row loss in parallel index build dual-cursor desync (#7176)

http://jira.cubrid.org/browse/CBRD-26799
Overview
btree_sort_get_next_parallel (added in parallel index build path from CBRD-26678 / PR #7011) maintains two scan cursors:

Slot cursor sort_args->cur_oid — advanced by heap_next_1page
Page cursor sort_args->curr_sec / curr_pgoffset — advanced by get_next_vpid

When SORT_REC_DOESNT_FIT (nofit) occurs, bt_load_put_buf_to_record rewinds cur_oid to prev_oid at the function entry point. However, if a heap page transition occurred within the same invocation, the slot cursor rewinds to the previous page while the page cursor already points to the next page. In the following invocation, the unconditional (*offset)++ in get_next_vpid skips the next page entirely, causing approximately one heap page worth of rows to be missing from the built B-tree.
As a result, CREATE INDEX executed via the parallel path intermittently (approximately 6/100 times) creates an index missing approximately 180–250 entries. A regular count(*) heap scan is normal, and the loss is only revealed through index scans (e.g., INDEX_SS). The serial path btree_sort_get_next is unaffected because it has only one cursor.
Implementation

Snapshot cur_oid to a local variable slot_resume_oid immediately before each heap_next_1page call.
At the nofit label, realign cur_oid to the page of vpid (using slot_resume_oid, or slot 0 of vpid if null). This prevents the slot cursor and page cursor from becoming misaligned.
Only src/storage/btree_load.c was modified; the serial path remains unchanged.

Testing

Release build, reproduction script failure.sql: 562/562 runs successful (approximately 6/100 failures before the fix)
In all executions, select count(*) from t (heap scan) was normal — before the fix, the heap was intact; only the built index was deficient

* [CBRD-26722] Expand parallel heap scan to parallel scan (index, heap, list) (#7062)

http://jira.cubrid.org/browse/CBRD-26722
Purpose
We will extend parallel scanning (parallel_heap_scan), which was previously applied only to heap scans, to list scans and index scans, and generalize it to enable parallel processing for all three scan types used in the query executor (S_HEAP_SCAN, S_LIST_SCAN, S_INDX_SCAN).
We will restructure the parallel_heap_scan namespace in src/query/parallel/px_heap_scan/ as parallel_scan in src/query/parallel/px_scan/, and add list/index input partitioners and slot iterators on top of the manager<RESULT_TYPE, SCAN_TYPE> template. Result collection (result_handler), worker management, interrupt, and trace are reused as common code regardless of the scan type.
The goal is to achieve performance gains through parallelization in large-scale scans (not only heap, but also intermediate result lists and index ranges).
Implementation
Please refer to the review document.

* Update tc-merge-gate.yml for remove feature branch in target scope.

* [CBRD-26202] Add Optimizer Histogram Support (#7180)

http://jira.cubrid.org/browse/CBRD-26202

- Purpose
Add histogram statistics support for optimizer selectivity estimation in CBRD-26202.

This change introduces histogram creation/query/client modules, adds SQL syntax for histogram create/drop/query, and adds related system catalog/view objects. It also integrates histogram statistics into optimizer selectivity estimation for equality predicates, range predicates, and LIKE predicates.

The work touches parser, lexer, semantic checks, name resolution, catalog, execution path, sampling scan, and optimizer paths.

Histograms can be created/dropped according to schema rules, and the optimizer uses them to improve cardinality estimation quality.

- Implementation
Implemented end-to-end histogram support across syntax, metadata, execution, and optimization paths
Please refer to the review document for detailed design decisions and code-level breakdown.

* [CBRD-26833] fix PRINT_OWNER_NAME macro (#7211)

http://jira.cubrid.org/browse/CBRD-26833

* fix PRINT_OWNER_NAME macro

* [CBRD-26800] refactoring boot_cl (#7178)

<http://jira.cubrid.org/browse/CBRD-26800>

* [Refactoring boot_cl.c for better readability and maintainability

* [CBRD-26761] Reduce sampling scan I/O by pre-picking pages via ftab metadata (#7136)

http://jira.cubrid.org/browse/CBRD-26761

Purpose
Reduces the number of page fix operations in the sampling scan path (SELECT /*+ SAMPLING_SCAN */ ... and the UPDATE STATISTICS code path) from "every page" down to "sampled pages only".

Previously all pages in the heap were fixed and loaded into the buffer pool, then rows were sampled at fixed intervals. The problem is that intermediate pages were fixed merely to follow the next page VPID (HEAP_CHAIN.next_vpid), even though they were never used for sampling. The more pages a table has, the more page fixes grow in proportion to the page count.

By reusing the ftab (file-allocation bitmap) metadata that parallel heap scan already maintains, sample VPIDs can be pre-picked without fixing any page. So we first pick the VPIDs of the pages to sample and then fix only those pages.

Partitioned tables are not sampled per partition; instead, after pruning, all partitions are gathered and the sample is taken table-wide in one pass, then split into per-partition slices. A small table that does not reach the sampling floor is simply scanned in full.

Implementation
Move the ftab module into storage (px_ftab_set.hpp → src/storage/ftab_set.{hpp,cpp})

ftab is a storage-layer data structure, so it was moved out so it can be used outside query/parallel, and the namespace was cleaned up. The include/type references at the call sites were updated as well, and no alias was left behind.
Add collect_strided_vpids_multi (ftab_set.cpp)

Merges the ftab bitmaps of several HFIDs (the pruned partitions, or a single root HFID when non-partitioned) and walks them once to pick sample VPIDs. It only looks at metadata, with no page fix.
The sampling interval (weight) is decided by a bucketed formula over the accurate user-page total obtained from file_get_num_user_pages: weight = max(min(3, ceil(total/MIN)), max(total/MAX, 1)) (MIN_HEAP_SAMPLING_PAGES=5000, MAX_HEAP_SAMPLING_PAGES=10000). That is, roughly 1/3 (33%) sampling, weight=1 (full scan) below the floor, and the sample count capped near MAX above the ceiling.
The gaps are not a uniform stride but are scattered with a Poisson distribution (mean = weight) to reduce clustering bias. The seed is fixed, so the same input yields the same sample (deterministic, reproducible).
The heap header page (hfid->hpgid) is excluded from the pick — a sampled page must not read slot 0 (HEAP_HDR_STATS) as a data record.
Partition boundaries are emitted together as a prefix sum (part_offsets) so the result can be split into per-partition slices.
Wire sampling scan into the flow (query_executor.c, scan_manager.c, heap_file.{c,h})

sampling_info holds picked_vpids / picked_count / picked_cursor / part_offsets / slice_end / n_parts / partition_cursor / weight / prepared.
qexec_prepare_table_sampling gathers the pruned HFIDs and picks the sample once (the prepared flag prevents re-picking on reopen / cached re-execution).
qexec_init_next_partition sets the cursor to the corresponding slice (part_offsets[pc] .. part_offsets[pc+1]) on each partition switch.
heap_next_sampling pulls pages one by one from the picked array by cursor instead of chain traversal. The chain-traversal helper heap_vpid_skip_next lost its callers, so its definition and extern were both removed.
The pick arrays (picked_vpids / part_offsets) persist across partition switches, and scan_free_sampling frees them once via qexec_clear_access_spec_list (XASL teardown) and the open-error path.

* [CBRD-26804] Raise pgbuf tracker max re-fix from 16 to 400 (#7222)

http://jira.cubrid.org/browse/CBRD-26804

Raised the limit from 16 to 400 to align with the default value of max_recursion_sql_depth. No resource-related side effects (re-fixing the same page only pins the same frame multiple times).

* [CBRD-26713] Resolve DMRB corruption by fixing race condition during context migration. (#7205)

Resolve DMRB corruption by fixing race condition during context migration.

* [CBRD-26764] Remove the controller entry point to prevent permission issues. (#7189)

* Remove the controller entry point to prevent permission issues.
* Exclude the members from compilation
* Exclude the header file

* [CBRD-26840] Suppress FORCE_FIXED_SCAN when scan pipeline acquires row locks (#7227)

http://jira.cubrid.org/browse/CBRD-26840

If any scan in the pipeline requires a lock (i.e., ACCESS_SPEC_FLAG_FOR_UPDATE or force_select_lock), we disable FORCE_FIXED_SCAN only in that case.

* [CBRD-26859] Qualify information_schema-owned class names with owner in CAS schema info (#7234)

http://jira.cubrid.org/browse/CBRD-26859

- CAS schema-info APIs now expose information_schema-owned classes as information_schema.<class_name> instead of the bare class name.
- Previously only user (non-system) classes were owner-qualified, so information_schema classes — classified as system classes — were returned unqualified; this corrects that.
- Consolidated the duplicated owner-qualification logic across the schema-info query paths into a single shared definition.

* [CBRD-26006] Scale Range Expansion and Floating-Point NUMERIC Type Support (#6486)

http://jira.cubrid.org/browse/CBRD-26006

Expand the scale range, introduce variable-length storage, add a Floating-Point
NUMERIC type, and optimize performance to improve the range and precision of
the existing NUMERIC type.

Key changes

* Expand the supported precision/scale range and adopt Oracle-style
  precision/scale interpretation
  * Fixed Numeric: precision 1–38, scale -84 to 127
  * Floating-Point NUMERIC: precision 1–40, scale -214 to 252

* Change Fixed Numeric storage from a fixed 16-byte format to a
  precision-based variable-length format
  (bytes = ceil(precision / log10(256)))

* Add a Floating-Point NUMERIC type
  * Interpreted as Floating-Point NUMERIC when the domain precision is
    DB_DEFAULT_NUMERIC_PRECISION (40)
  * Uses precision and scale stored in the data header rather than the domain
  * Stored as a 3-byte header plus variable-length payload
  * Behaves as Floating-Point NUMERIC when NUMERIC is unspecified

* Arithmetic
  * Add DB_TYPE_NUMERIC-specific fp_numeric_db_value_(add|sub|mul|div),
    supporting arithmetic beyond 38 digits and rounding results that exceed
    the target precision
  * Keep legacy numeric_db_value_* for SERIAL/SHORT/INTEGER/BIGINT only
  * Add hybrid normalization for Hash Join
    (Fixed↔Floating-Point combinations resolve to Floating-Point NUMERIC)

* Performance optimization
  * Sign handling: two's complement → managed via a domain flag; data is
    always stored as an absolute value
  * Arithmetic redesigned from byte-wise processing to uint64_t-based
    word operations
  * Knuth division / Horner's method / 10^16 chunking and LUT for type casts /
    bigint fast path

* Fix a bug where invalid-format string literals could be silently converted
  to incorrect values during NUMERIC coercion
  (added validation for duplicate decimal points, digit presence, and
  characters following trailing spaces)

Related issues

* [CBRD-26243] (Phase-1) Scale Range Expansion (1/2) (#6385)
* [CBRD-26317] (Phase-1) Arithmetic Operations and Built-in Functions for
  Extended Scale Range (2/2) (#6520)
* [CBRD-26367] (Phase-2) NUMERIC Storage Format Optimization (#6623)
* [CBRD-26397] (Phase-3) Floating-Point NUMERIC Type Support (#6671)
* [CBRD-26575] (Phase-4) NUMERIC Performance Optimization (#6881)
* [CBRD-26749] Strengthen NUMERIC Parsing Rules

Compatibility (Breaking Changes)

* Fixed Numeric and Floating-Point NUMERIC storage formats are not backward
  compatible
  (migrate lower-version Fixed Numeric and SERIAL values via unload/load)

* Removed parameters:
  * compat_numeric_division_scale
  * stored_procedure_return_numeric_size
* The default value of oracle_compat_number_behavior (yes/no) will be
  determined separately before the Guava release

* [CBRD-26827] Fix SIGSEGV in pt_print_dblink_table when server name is quoted (#7203)

http://jira.cubrid.org/browse/CBRD-26827

* [CBRD-26812] Handle resource allocation failure during connection pool initialization. (#7194)

* Add guards to handle resource allocation failure.

* [CBRD-26838] Remove repetitive re-allocation for char * in a same scope (#7206)

http://jira.cubrid.org/browse/CBRD-26838

Purpose
This pull request aims for micro optimization when repetitive strlen/strcat/strcpy call happens.

Implementation
O(N^2) strlen => O(N) strlen, temporary variable
strcpy->strcat->strcat => strcpy->snprinf or snprintf, temporary len variable
extraneous malloc => strdup

* [CBRD-25863] Correct Information Schema Specs (#7241)

http://jira.cubrid.org/browse/CBRD-25863

- Widen the default-expression columns (COLUMNS.column_default, PARAMETERS.parameter_default, DOMAINS.domain_default) from 255 to 2048 to match the underlying catalog columns widened by CBRD-26676, preventing truncated values.
- Change COLUMNS.is_generated from the non-standard 'NO' to the SQL-standard 'NEVER', and widen the column so the standard value set ('NEVER'/'ALWAYS') fits without truncation.
- DOMAINS.domain_default is widened for spec consistency only; the view always emits NULL for it.

* [CBRD-26610] Extend broker_log_top features with broker.conf collection and split output by broker (#7242)

http://jira.cubrid.org/browse/CBRD-26610

- Add '--from-conf' option to parse and collect log files from $CUBRID/conf/cubrid_broker.conf.
- Add '-S / --split' option to generate results per broker into separate hierarchical directories (broker_log_top_YYMMDD_HHMM/broker_name/).

* [CBRD-26845] To disable type checking for NA fields in queries generated by unloaddb (#7220)

http://jira.cubrid.org/browse/CBRD-26845

* [CBRD-23839] Fix race condition in unloaddb.sh schema unload (#7243)

http://jira.cubrid.org/browse/CBRD-23839

[CBRD-23839] Fix race: wait for the backgrounded schema unload

do_unloaddb() ran the schema unload in the background ('&') but never waited
on it. The final 'wait' only tracks the per-slot worker subshells, and each
waited only on its data-unload PID, so the schema unload was orphaned and the
schema files could still be incomplete when "Completed." was printed (an
intermittent failure under load).

Capture the schema unload PID and wait on it before the worker returns (on
both the schema-only and the schema+data paths), so the schema files are
complete before "Completed.". The schema unload still runs concurrently with
the data unloads, preserving the parallel design.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>

* [CBRD-26839] Emit zero-stats parallel heap scan trace when no worker stats collected (#7219)

http://jira.cubrid.org/browse/CBRD-26839

  Problem:

  In the trace output of a parallel heap scan, when no statistics have been collected at all, the sentinel value (numeric_limits<UINT64>::max()) was being exposed as-is. When zero rows are returned (e.g., via
  LIMIT 0), accumulative_trace_storage::m_stats is empty, so the min-reduction loop never executes, and the initial value was printed verbatim as 18446744073709551615..0.

  ---
  Change:

  Added an m_stats.empty() early-return guard to the two dump functions — dump_stats_text and dump_stats_json — in src/query/parallel/px_heap_scan/px_heap_scan_trace_handler.cpp. When empty, the loop is skipped
  and all statistics are output as 0.

  ---
  Repro / verification:

  ;trace on
  SELECT COUNT(*) AS cnt
    FROM (SELECT id FROM t_px_sort ORDER BY id LIMIT 0) sub;

  Result:

          SCAN (table: dba.t_px_sort), (heap time: 0, fetch: 0, ioread: 0, readrows: 0, rows: 0)
               (parallel workers: 0, heap time: 0..0, readrows: 0..0, rows: 0..0, gather: mergeable list)

  Matches the expected output in JIRA.

* [CBRD-26599] Implement Join Predicate Push-down via Transitive Closure (#6917)

http://jira.cubrid.org/browse/CBRD-26599

Add implied join terms derived from the transitive closure of equi-join predicates so the optimizer can explore join orders that were previously unreachable for lack of a direct join edge.

* http://jira.cubrid.org/browse/CBRD-26851

* [CBRD-26612] Resolve estimated_*/INDEX_CARDINALITY class name by current schema (#7251)

http://jira.cubrid.org/browse/CBRD-26612

- Allow the estimated_table_rows / estimated_avg_row_length / estimated_data_length / estimated_data_free functions and INDEX_CARDINALITY to accept a bare table name (without owner) and resolve it against the current schema.
- Previously these matched the server's exact unique_name (owner.name), so a call such as estimated_table_rows('t1') failed the lookup and returned NULL; bare names now work as expected.
- Qualify constant string-literal class-name arguments with the current schema name during type checking, following the same rules as ordinary table references. Arguments already in owner.name form, system class names, and the unique_name column values passed by INFORMATION_SCHEMA views are left unchanged.

Server-side evaluation logic is unchanged; only client-side name qualification is added.

* [CBRD-26888] Fix debug assert crash in midxkey prefix compression (#7264)

http://jira.cubrid.org/browse/CBRD-26888

In midxkey prefix compression, even when the postfix offset is valid,
if the merged key (postfix offset + prefix) exceeds 255 bytes, a
legitimate break path was missing from the assert condition, causing
cub_server to dump core only in debug builds.

Add the missing condition (offset + prefix_size) >= OR_MULTI_MAX_OFFSET
to the assert. This only supplements the debug assert with no behavioral
change.

- Not a regression: present since midxkey compression was introduced
  (CBRD-24988, 2023); unrelated to char-vlen.
- Repro: long_checkpoint_dml_ddl.sh (RQG); intermittent, key-length dependent.

* Update config.yml for show all file list from extract CUBRID artifact.

* [CBRD-26663] CHAR/VARCHAR unified variable-length storage (feature → develop) (#7164)

https://jira.cubrid.org/browse/CBRD-26663

Convert CHAR storage from fixed-length to variable-length and unify the
CHAR/VARCHAR header to remove the O(N) character-scan overhead on the
CHAR(N) UTF-8 readval path.

Background:
CHAR(N) UTF-8 allocates a fixed precision*4 bytes on disk and fills the
remaining space with 0x20. Because both the trailing pad and the unused
space are 0x20 and no byte-length information is stored on disk, every
readval had to walk the value character by character via intl_char_size ->
intl_nextchar_utf8 (O(N)) to compute the valid byte length. Profiling
showed this path accounted for about 49% of total CPU, roughly 90x more
expensive than the actual value comparison (0.55%). VARCHAR has the same
structural issue, requiring an O(N) intl_char_count scan for
character-based operations such as LENGTH() and SUBSTRING().

Changes (3 steps):

Step 1 (CBRD-26706): Move CHAR from fixed-length to variable-length storage
- Convert CHAR storage from fixed length (precision*4 byte) to a variable
layout
- Introduce a 12-byte LARGE header (length / size / compressed_size)
- Look up the byte size in O(1) from the header's size field on readval,
eliminating the intl_char_size call
- Remove the trailing (domain) pad; keep the char pad used for
trailing-space comparison
- Set tp_Char.variable_p = 1 to share the same variable-attribute flow as
VARCHAR
- Allow CHAR midxkey elements in pr_midxkey_element_disk_size

Step 2 (CBRD-26762): Unify CHAR/VARCHAR headers and enable CHAR compression
- Merge the CHAR/VARCHAR hot-path functions into mr_*_char_type_common
(remove duplication)
- Add length (char_count) to the unified string header for O(1)
character-based operations
- Enable CHAR compression (LZ4) on the same compression path as VARCHAR
- Add or_put/get_string_header helpers
- Fix regressions caused by the previous VARCHAR-only assumptions
(CHAR double-free, CONNECT BY misbehavior, loaddb crash, missing
result-set compression check, etc.)

Step 3 (CBRD-26763): Introduce variable headers (Tiny/Small/Medium/LARGE)
- Resolve the header overhead of short strings caused by the single
12-byte LARGE header
- Use 4 header types (1/4/6/12 bytes) depending on size; empty string goes
from 16 to 4 bytes
- Add or_string_pick_header_type / or_mem_string_pick_header_type dispatch
helpers
- Change or_varchar_length / or_packed_varchar_length signatures to
(length, size, csize)

Effect:
Removes the intl_char_size / intl_nextchar_utf8 overhead on the CHAR(N)
UTF-8 readval path, enables O(1) access for character-based operations
such as LENGTH()/SUBSTRING(), and improves storage efficiency for short
strings.

Compatibility:
CHAR comparison, network transfer, and query results are unchanged, and
backward compatibility with existing data is preserved.

Verification:
All existing CHAR-related SQL tests (comparison, string functions, sorting,
index scan) pass, correctness was verified on multibyte (Korean/emoji) CHAR
columns, and profiling shows a reduced share of intl functions.

* [CBRD-26887] Fix NULL variable-length NUMERIC over-read crash in unloaddb (#7263)

http://jira.cubrid.org/browse/CBRD-26887

After FP NUMERIC made numeric variable-length, NULL numerics are stored as
zero-length slots. mr_data_readval_numeric did not handle size == 0, so
unloaddb misread garbage as the numeric body, shifting the following CHAR
read and overrunning the record buffer (assert in or_advance during
get_desc_current -> data_readval_string).

varchar already treated size == 0 as NULL; numeric did not. Restore symmetry
by adding size == 0 to the NULL branch (or_advance(buf, 0)).

- precision == 0 branch kept for backward compat (numeric(0,0) -> NULL).
- Use or_advance(buf, 0), not db_value_domain_init(): init treats precision 0
  as invalid (ER_INVALID_PRECISION, overwrites to 38/15). Caller pre-inits
  with db_make_null, so or_advance(buf, 0) is a NULL-preserving no-op.
- DB_TYPE_NUMERIC check needed: VARIABLE also has precision 0.

Surfaced by moving CHAR into the variable section (NULL numeric + variable CHAR).

Verification: 32x unload no crash, round-trip 200/200, minimal repro passes.

* [CBRD-26893] Fix uninitialized class pointer dereference in IS NOT NULL predicate folding (#7265)

http://jira.cubrid.org/browse/CBRD-26893

- Fix a crash (SIGSEGV) when folding an IS NOT NULL predicate on a class whose
  metadata cannot be fetched: the optimization now gives up safely instead of
  dereferencing an uninitialized class object.

* [CBRD-26755] Reduce poll() overhead in css_readn and css_vector_send via optimistic I/O fast-path (#7215)

http://jira.cubrid.org/browse/CBRD-26755

Try recv/writev first and call poll() only when the socket is not ready, avoiding an unnecessary syscall on the hot path.

* [CBRD-26864] Prevent owner change when renaming a table via ALTER TABLE by adding the missing owner-change check (#7250)

http://jira.cubrid.org/browse/CBRD-26864

Add the owner-qualifier check to `do_alter_clause_rename_entity()` that the **RENAME TABLE** path already had, raising `ER_SM_RENAME_CANT_ALTER_OWNER` when the old and new owners differ.

* [CBRD-26870] Set DBLink remote column collation to match its codeset (#7253)

http://jira.cubrid.org/browse/CBRD-26870

DBLink remote columns filled codeset from CCI metadata but left collation_id at
its default 0 (LANG_COLL_ISO_BINARY), since CCI exposes a column's charset but
not its collation. A remote UTF8 column then kept an ISO88591 collation, breaking
the pt_check_expr_collation() invariant that an equal collation_id implies an
equal codeset (debug: assertion failure; release: silent wrong results).

Assign the codeset's binary collation in pt_dblink_table_fill_attr_def() so
collation_id and codeset stay consistent.

* [CBRD-26906] USE INDEX hint ignored — optimizer picks sequential scan over the hinted index (#7273)

http://jira.cubrid.org/browse/CBRD-26906

Ensure USE INDEX hint is honored by excluding sequential scan from consideration, preventing cost-based selection of seq scan over the hinted index.

* [CBRD-26863] Fix parallel index scan overflow-chain deadlock vs concurrent DML/DDL (#7239)

http://jira.cubrid.org/browse/CBRD-26863

**Purpose**

This change fixes a deadlock-induced hang that can occur during parallel index scans when DML/DDL operations (such as DELETE page splits, DROP deallocation, vacuum, etc.) are executed concurrently on the same index.

The root cause is that the overflow chain pool invokes `pgbuf_fix()` while holding `m_overflow_mutex` (a C++ `std::mutex`). The normal lock acquisition order is **leaf latch → overflow latch**. However, refixing a leaf page while inside the mutex reverses the order. Since this mutex is not represented in the pgbuf deadlock detection graph, the resulting deadlock cannot be detected or resolved automatically and becomes a permanent hang.

**Implementation**

### Key-publish approach

The producer now deep-copies the key into `overflow_slot` while holding the leaf S-latch. Helpers only duplicate the key from the slot and no longer refix the leaf page.

The previous helper path involving `spage_get_record()` and `btree_read_record()` has been removed, eliminating the possibility of leaf-page fixes while holding `m_overflow_mutex`.

The `overflow_slot` structure has been updated by removing `leaf_vpid` and `leaf_slot_id`, and adding the key (`DB_VALUE`) together with a `clear_key` flag.

### Moving page fixes outside the mutex

`claim_next()` now snapshots only the cursor state while holding the mutex. After releasing the mutex, it fixes the overflow page using `PGBUF_UNCONDITIONAL_LATCH`.

Both writers and vacuum workers acquire latches in the normal **leaf → overflow (top-down)** order, so performing the page fix outside the mutex does not introduce lock cycles. In addition, parallel scans do not use latch coupling, so a conditional latch is unnecessary.

### Concurrency-related improvements

* Introduced `close_slot_locked()` to centralize slot cleanup (key release, field reset, and notification), preventing key lifetime leaks and double-free issues.
* Added a per-slot `claim_in_flight` flag to prevent multiple helpers from processing the same overflow page concurrently.
* Cursor advancement now occurs exactly once after a successful page fix.
* It is valid for another producer to publish work after `signal_no_more_leaves()` has been issued. Therefore, the assertion in `try_publish()` has been relaxed to check `m_active_workers > 0`.

The changes are limited to `src/query/parallel/px_scan` and do not modify the core B-tree concurrency protocol.

**Remarks**

* Verified that debug builds produce no warnings.
* Confirmed that there are no remaining `pgbuf_fix()` calls while holding either `m_overflow_mutex` or `m_leaf_mutex`.
* Verified parallel/serial consistency:

  * Overflow duplicate-key scenarios produce identical results.
  * `COUNT` results (2000) and `GROUP BY` results (400 × 5) match between parallel and serial execution.
* Due to environment limitations, the following validations were not performed:

  * Long-running stress tests under real concurrent workloads to verify the absence of hangs or core dumps.
  * Memory leak verification using ASAN or Valgrind.

* [CBRD-26805] Fix the HY010 Error During DBLink Operation (#7257)

Fixes intermittent errors that occurred in the CAS/CGW (ODBC) path when executing DML operations (such as INSERT) on a remote MySQL database through DBLink.

Symptom 1: SQLRowCount() returns -1, and the client displays the error message "Number of rows affected is unknown".
Symptom 2: [HY010] Function sequence error occurs.

* [CBRD-26838] Replace malloc+strcpy with strdup where safe (#7254)

* [CBRD-26838] Replace malloc+strcpy with strdup where safe

* lint: remove dead if condition

* [CBRD-26889] Lower ISCAN_OID_ACCESS_OVERHEAD from 20 to 5 to favor index scan

http://jira.cubrid.org/browse/CBRD-26889

Lower the per-OID heap access CPU penalty constant (ISCAN_OID_ACCESS_OVERHEAD) for non-covering index scans from 20 to 5 to favor index scans.

* [CBRD-26880] Fix DBLink remote bind for FLOAT, DATETIME, and typed NULL values (#7255)

http://jira.cubrid.org/browse/CBRD-26880

Fix three type-handling bugs in dblink_bind_param (src/query/dblink_scan.c)
that corrupted host-variable (?) binding to remote servers: FLOAT was bound
through the DOUBLE path (4-byte value read as 8-byte → ≈0), DATETIME passed
month/day/year to db_datetime_decode in the wrong order, and a typed NULL
(domain type + null flag) fell into its domain branch instead of binding as
NULL. Bind FLOAT via CCI_U_TYPE_FLOAT, fix the DATETIME_DECODE argument order,
and route any null dbval to the DB_TYPE_NULL branch.

* [CBRD-26841] issue length limit auto generated name for long table name (#7230)

http://jira.cubrid.org/browse/CBRD-26841

* [CBRD-26841] Issues with length limits on automatically generated names for long table names
* Restrict the length of auto-increment serial names to avoid excessive length
* An error is handled if the serial name automatically generated by the AUTO_INCREMENT attribute exceeds the serial name length limit.
* An error is handled if the internal table name automatically generated by the table's partition attribute exceeds the table name length limit.

* [CBRD-26894] Fix core dump in er_message::set_error during histogram stat collection (#7270)

http://jira.cubrid.org/browse/CBRD-26894

[CBRD-26894] Fix wrong er_set (ER_FAILED) in obj_find_multi_attr Regression of CBRD-26202.

obj_find_multi_attr() called er_set(..., ER_FAILED, 0) on BTREE_ERROR_OCCURRED. ER_FAILED is not a settable error id, so it trips the assert in cuberr::er_message::set_error() and cores the client during histogram stat collection.

* [CBRD-26825] View query execution error including CONNECT BY query (#7209)

http://jira.cubrid.org/browse/CBRD-26825

---------

Co-authored-by: tw-kang <twkang3219@gmail.com>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Co-authored-by: Ilhan <70995854+xmilex-git@users.noreply.github.com>
Co-authored-by: Joo Youngjin <68979537+youngjinj@users.noreply.github.com>
Co-authored-by: Kisoo Han <kisoo-han@cubrid.com>
Co-authored-by: Hyung-Gyu Ryoo <hgryoo@cubrid.com>
Co-authored-by: Mike MyungHwan Oh <mhoh@cubrid.com>
Co-authored-by: Byungwook Kim <bwkim@cubrid.com>
Co-authored-by: KIM HUISU <heexoo@cubrid.com>
Co-authored-by: Kwang Soo Chae <kchae@cubrid.com>
Co-authored-by: kangmin <kangmin5505@gmail.com>
Co-authored-by: Na, Hyunik <67700070+hyunikn@users.noreply.github.com>
Co-authored-by: ctshim <78332782+ctshim@users.noreply.github.com>
Co-authored-by: SE park <shpark@cubrid.com>
Co-authored-by: Daehyun Kim <dhkim@cubrid.com>
Co-authored-by: CUBRID <cubridci@users.noreply.github.com>
Co-authored-by: 정소희 <94791489+sohee-dgist@users.noreply.github.com>
Co-authored-by: jongmin-won <55681111+jongmin-won@users.noreply.github.com>
Co-authored-by: 이윤진(Lee Yunjin) <168180007+gg582@users.noreply.github.com>
Co-authored-by: Hyunuk Lee <41990473+HyunukLee@users.noreply.github.com>
Co-authored-by: airnet73 <61675061+airnet73@users.noreply.github.com>
ssihil added a commit to CUBRID/cubrid-testcases that referenced this pull request Oct 13, 2026
… parallel execution support (#3594)

- Issue: http://jira.cubrid.org/browse/CBRD-26719
- Engine PR: CUBRID/cubrid#7068
- **관련 TC:** 별도 PR로 분리 — CUBRID/cubrid-testcases-private-ex#4264. 진입 조건 **(3) 공유 워커 풀 예약 성공** 은 여러 세션이 동시에 풀을 다투어야 실패하므로 단일 세션인 SQL 러너로는 도달 불가

## 개요

파티션이 만들어지지 않는 **single-context 경로**에서 probe 단계를 N 개 워커로 나눠 처리하는 기능으로,
build 를 마친 primary 가 해시 테이블을 소유하고 secondary context 들이 이를 공유하면서 probe 측
list_id 페이지를 섹터 단위로 나눠 가져갑니다.

답지는 **`11.5.0.2622-e1c3db1`** 에서 생성했습니다.

## 트레이스 판별 기준

이 기능은 기존 **파티션 기반 병렬**과 트레이스 모양이 다릅니다.

| 모드 | 트레이스에 나타나는 모습 |
|---|---|
| **probe 병렬** (본 이슈) | `PROBE` 라인 **바로 다음 줄** 에 `(parallel workers: N, time: a..b, readrows: .., readkeys: .., rows: ..)`. `HASHJOIN` 라인에는 `parallel workers` 가 **없고** `SPLIT` 도 없음 |
| 파티션 병렬 (CBRD-25717) | `HASHJOIN` 라인의 `parallel workers` + `SPLIT` + `PARALLEL` 노드 |
| **이 기능과 무관한 병렬 표기** | hash join 이 아닌 다른 병렬 기능도 `parallel workers` 서브라인을 남김. parallel heap scan 은 `SCAN (table: …)` 아래 `(parallel workers: N, heap time: …, gather: mergeable list)`, 집계 gather 는 `SCAN (temp …)` 아래 `(parallel workers: N, temp time: …, gather: buildvalue)`, parallel subquery 는 `SUBQUERY (uncorrelated)` 아래 `(parallel workers: N, time: …, fetch: …)`. 셋 다 `readkeys:` 가 없고 `PROBE` 아래가 아니라는 점에서 probe 병렬과 구분됨. 답지 `07`·`08`에 각 3건, `15`에 22건이 남아 있고 나머지 12종은 `no_parallel_scan` / `no_parallel_subquery` 로 억제해 0건 |

## Acceptance Criteria 커버리지

| A/C 항목 (JIRA 원문) | 검증 케이스 |
|---|---|
| ① single-context 경로에서 probe-level parallel 이 활성화되는 조건에서, 병렬 실행 결과가 동일 질의의 single-thread 실행과 동일한 행 집합을 생성 | `01`·`02`·`03`·`04`·`09`·`10` (parallel 결과와 serial 결과를 EXCEPT 로 양방향 대조, 모두 0건), `11`·`14`·`15` **(추가, 같은 방식)**. `05` 와 `12`·`13` **(추가)** 는 집계값 일치로 확인 |
| ② Inner / left-outer / **right-outer** join 의 NULL-fill 및 during_join_pred residual 평가가 parallel probe 경로에서도 single-thread 와 동일 | `01`(inner), `02`·`04`(left-outer), **`11` (추가, right-outer)** |
| ③ parallel probe 가 활성화된 실행의 trace / JSON dump 에 PROBE worker 범위(time / readrows / readkeys / rows min..max) 가 기록되고, 파티션 기반 parallel 과 상태로 구분 | `01` (text + JSON), `07` (파티션 경로와 대비, 역시 text + JSON) |

진입 조건(하나라도 실패 시 단일 스레드 fallback)도 함께 다룹니다.

| 진입 조건 | 검증 케이스 |
|---|---|
| (1) single-context 경로 — 파티션 재진입 아님 | `07` (파티션 경로에서 probe 병렬이 **추가 발동하지 않음**) |
| (2) probe 측 페이지 수와 요청 병렬도로 계산한 degree ≥ 2 | `06` (힌트로 요청 병렬도를 0 또는 1 로 낮춰서), **`12` (추가, 데이터 크기로)** |
| (3) 공유 워커 풀 예약 성공 | **shell PR** — `https://github.com/CUBRID/cubrid-testcases-private-ex/pull/4264` (여러 세션이 동시에 풀을 다투어야 실패하므로 단일 세션인 SQL 러너로는 도달 불가) |

## 케이스 목록 — `sql/_36_guava/cbrd_26719/{cases,answers}` (15종)

> 표기 **(추가)** 는 JIRA 첨부에 없는 자체 추가분입니다. 표기가 없는 케이스는 첨부 기반입니다.

| 케이스 | 검증 내용 |
|--------|-----------|
| `01_inner_baseline` | INNER 조인 기본 케이스. text / JSON 두 트레이스와 parallel↔serial EXCEPT 양방향 0건 |
| `02_left_outer_baseline` | LEFT OUTER 의 NULL-fill 이 워커 사이에 정확히 분배 (residual 없는 순수 OUTER) |
| `03_probe_overflow_tuple` | probe 리스트 파일의 튜플 하나가 `QFILE_MAX_TUPLE_SIZE_IN_PAGE`(16K 페이지에서 16,352B) 를 넘어 overflow 체인이 생기는 상태에서의 섹터 순회. `bit(32000)×8 = 32,000B` 을 `no_merge` 로 투영해 리스트에 싣는 구성 |
| `04_outer_during_pred` | LEFT OUTER + during_join_pred. residual 평가가 워커별로 격리되어 NULL-fill 카운트가 직렬과 일치 |
| `05_bind_user_var_pred` | during_join_pred 의 bind 변수 / user 변수가 워커에 정확히 전달 |
| `06_fallback_serial` | `PARALLEL(0)`/`PARALLEL(1)`/`NO_PARALLEL_HASH_JOIN` 으로 진입 조건 (2) 에 걸려 단일 스레드로 fallback. **SPLIT 이 나오면 파티션으로 잘못 샌 회귀** |
| `07_partition_reentry_guard` | 파티션 경로에서 probe 병렬이 **재발동하지 않아야 함**. SPLIT + PARALLEL 만 나오고 PROBE 서브라인은 없어야 함 |
| `08_empty_input_outer` | 한쪽 입력이 빈 OUTER → NULL-fill 전용 경로. build/probe 단계를 거치지 않으므로 probe 병렬 **비적용 대상** |
| `09_nested_parallel_probe` | 한 쿼리에 hash join 2개, 각 build 가 작아 둘 다 single-context. 두 노드 모두 probe 병렬. 기본 워커 풀에서는 둘 다 워커를 확보하므로 **풀 예약 실패 경로는 여기서 실행되지 않음** (shell PR 이 담당) |
| `10_probe_key_coerce` | build 키 `varchar` vs probe 키 `char` → probe 마다 `tp_value_coerce` → `qstr_coerce` 가 발생. 변환 버퍼가 per-task `resource_tracker` scope 에 잡히므로, task 밖에서 해제하면 디버그 빌드에서 restrack assert 가 발생. `14` 와는 다른 경로. `14` 의 Case 7·8 은 BIGINT↔INT 라 숫자 변환이어서 버퍼를 잡지 않음 |
| `11_right_outer` **(추가)** | **A/C ② 미커버 구간.** 첨부의 `right outer join` 은 `08` 의 빈 입력 케이스뿐인데 그 경로는 probe 병렬 비적용 대상이라, probe 병렬이 **실제로 도는 RIGHT OUTER** 가 없었음. NULL-fill + during_join_pred 변형까지 포함 |
| `12_degree_gate` **(추가)** | **진입 조건 (2) 미커버 구간.** `06` 은 힌트로만 진입 조건을 막는데, degree 는 probe 페이지 수로도 결정됨. 힌트는 `PARALLEL(4)` 로 두고 **probe 크기만 바꿔** probe 가 작을 때의 fallback 과 클 때의 발동을 한 파일에서 대조 |
| `13_probe_distribution` **(추가)** | 이 기능의 본질이 probe 입력 분배인데 첨부의 probe 데이터는 전부 균등 분포. **NULL 키 10% / N:M 중복 / 80% 편중** 세 형태를 추가 |
| `14_key_type_and_composite` **(추가)** | **키 처리 경로 미커버 구간.** 나머지 케이스는 조인 키가 전부 `int` 단일 키라, 워커별 키 버퍼를 채우는 `hjoin_fetch_key()` 의 세 분기 — 다중 `key_index` 루프(복합키), `need_coerce_domains` 코어션, 가변길이 값의 `pr_clear_value` 수명주기 — 가 한 번도 실행되지 않음. 고정폭 VARCHAR / 가변길이 VARCHAR / 복합키(int+VARCHAR) / BIGINT↔INT 불일치 네 가지에 더해, VARCHAR 키 LEFT OUTER 에서 20% 가 NULL-fill 되는 경우까지 확인 |
| `15_probe_dependent_list` **(추가)** | **섹터 수집 미커버 구간.** probe 섹터는 `qfile_collect_list_sector_info()` 가 모으는데, 이 함수는 `dependent_list_id` 체인을 순회함. probe 를 UNION ALL 파생 테이블로 두어 체인을 만들어야 `tfiles[]` 가 다항목이 되고, `03` 이 경고한 "잘못된 tfile 반환" 시나리오가 성립(`03` 은 단일 tfile). CBRD-25717 의 `sector_dependent_list` 는 같은 함수를 **split 단계**에서 확인했고, 이 케이스는 **probe 단계** 버전이라 **SPLIT 이 0** 이어야 함 |
| `16_null_probe_key_outer` **(추가)** | **NULL probe 키 갭(리뷰).** `hjoin_fetch_key()` 는 probe 키가 NULL 이면 해시 테이블을 안 뒤지고 바로 NULL-fill 하는 분기가 있는데, 13 의 NULL 키는 INNER(행 버림)이고 OUTER 케이스엔 NULL 키가 없었음. LEFT·RIGHT OUTER 에 10% NULL 키 → 280000/270000/10000 |
| `17_worker_error` **(추가)** | **워커 오류 전파/정리 갭(리뷰).** during_join_pred 의 `cast(tag as int)` 가 한 행에서 실패 → 워커 오류가 세션까지 전파(`Error:-181`), 세션 생존(Case 3), 실패행 제외 시 정상(Case 4) |

## 첨부 이식 시 수정한 것

| 항목 | 내용 |
|---|---|
| `no_parallel_heap_scan` → `no_parallel_scan` | 4월 첨부의 **10곳**에 해당하던 항목. CBRD-26722 / #7062 에서 이름이 바뀌어 옛 키워드는 현행 빌드에서 **조용히 무시**되고, 그대로 두면 의도한 스캔 병렬 억제가 걸리지 않은 채 통과함. **9월 보완본에서는 개발자가 이미 반영**했으므로 현재 첨부 대비로는 수정 사항이 아님 |
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.

6 participants