Skip to content

Fix cursor pagination with ORDER BY returning zero items on subsequent pages - #3

Merged
makr-code merged 3 commits into
mainfrom
copilot/fix-150588092-1085539157-63ec51c6-6e96-4b34-a99a-9b67bd231ecf
Nov 5, 2025
Merged

makr-code merged 3 commits into
mainfrom
copilot/fix-150588092-1085539157-63ec51c6-6e96-4b34-a99a-9b67bd231ecf

Conversation

Copilot AI commented Nov 3, 2025 •

Copy link
Copy Markdown
Contributor

Cursor pagination with ORDER BY + LIMIT could return zero items on page 2+ when the query engine's cursor-anchored scan fetched exactly limit items, then equality predicates filtered some out post-positioning.

Changes:

  • HTTP server (src/server/http_server.cpp): Added safety margin to fetch limit for cursor queries

    constexpr size_t CURSOR_SAFETY_MARGIN = 5;
    size_t num_predicates = q.predicates.size();
    size_t safety_margin = (num_predicates > 0) ? CURSOR_SAFETY_MARGIN * num_predicates : CURSOR_SAFETY_MARGIN;
    q.orderBy->limit = requested_count_for_cursor + safety_margin + 1;

    Scales margin with predicate count to handle filtering after cursor positioning.

  • Test (tests/test_http_aql.cpp): Enhanced diagnostics to log full response bodies and cursor token when batch_size is zero.

Fixes job ref: 7e043e7ac8cba31c61c9812621298ea3ef7122b1

Original prompt

CI failing test: HttpAqlApiTest.CursorPagination_SecondPage (see job ref: 7e043e7, run: https://github.com/makr-code/ThemisDB/actions/runs/19028521897/job/54336950997).

Problem summary:

  • When using cursor-based pagination together with ORDER BY + LIMIT, the translator sets orderBy.limit = offset + count which can cause the engine to fetch fewer items than needed. Cursor skipping afterwards can result in 0 items on subsequent pages. The test expects page 2 to return at least one item and different items from page 1, but CI shows it may return zero items causing failure.

Goal of this PR:

  1. Implement a conservative server-side guard in the query translator to fetch extra items to account for cursor skipping so LIMIT+ORDER BY with cursor yields at least count items when possible.
  2. Add a defensive helper in tests so the failing test emits a clear failure message if server still returns 0 items, and avoid flaky CI by allowing a temporary diagnostic assertion (maintainers can revert when translator fix is validated).

Planned changes (high level):
A) Code change in query translator/planner:

  • Locate code where orderBy.limit is set when building a query with ORDER BY + LIMIT.
  • Adjust fetch limit calculation to include cursor skip estimate: fetch_count = requested_count + cursor_skip_estimate + 1 (the +1 for has_more detection).
  • If cursor skip estimate isn't available, add a small fixed guard (e.g., +2) to reduce likelihood of underfetch while avoiding huge reads.
  • Add unit tests for translator behaviour (if present) and comments explaining rationale.

B) Test change in tests/test_http_aql.cpp:

  • Update CursorPagination_SecondPage to log full response bodies for pages 1 and 2 on failure to aid debugging.
  • Add a clearer failure message when page 2 batch_size == 0 and avoid immediate hard-fail on CI by using ADD_FAILURE with diagnostic; keep primary expectations intact if non-zero.

C) PR description will reference the failing job ref: 7e043e7 for traceability.

Notes:

  • The translator change is the correct long-term fix (implementing seek-based cursor is best but larger work). This PR implements a conservative fetch-guard to make cursor pagination with ORDER BY+LIMIT behave more reliably.
  • If maintainers prefer only the translator change or only the test change, the PR can be split; this PR proposes both to get CI stable and add server-side mitigation.

Files to edit (to be discovered by the coding agent):

  • Translator/planner source(s) that set orderBy.limit (likely under src/query or src/aql or similar). Search repository for occurrences of "orderBy.limit" or where LIMIT handling is implemented.
  • tests/test_http_aql.cpp to add diagnostics and temporary defensive assertion.

Please create a branch, apply the changes, and open a pull request with this problem statement and reference the job ref in the PR description.

This pull request was created as a result of the following prompt from Copilot chat.

CI failing test: HttpAqlApiTest.CursorPagination_SecondPage (see job ref: 7e043e7, run: https://github.com/makr-code/ThemisDB/actions/runs/19028521897/job/54336950997).

Problem summary:

  • When using cursor-based pagination together with ORDER BY + LIMIT, the translator sets orderBy.limit = offset + count which can cause the engine to fetch fewer items than needed. Cursor skipping afterwards can result in 0 items on subsequent pages. The test expects page 2 to return at least one item and different items from page 1, but CI shows it may return zero items causing failure.

Goal of this PR:

  1. Implement a conservative server-side guard in the query translator to fetch extra items to account for cursor skipping so LIMIT+ORDER BY with cursor yields at least count items when possible.
  2. Add a defensive helper in tests so the failing test emits a clear failure message if server still returns 0 items, and avoid flaky CI by allowing a temporary diagnostic assertion (maintainers can revert when translator fix is validated).

Planned changes (high level):
A) Code change in query translator/planner:

  • Locate code where orderBy.limit is set when building a query with ORDER BY + LIMIT.
  • Adjust fetch limit calculation to include cursor skip estimate: fetch_count = requested_count + cursor_skip_estimate + 1 (the +1 for has_more detection).
  • If cursor skip estimate isn't available, add a small fixed guard (e.g., +2) to reduce likelihood of underfetch while avoiding huge reads.
  • Add unit tests for translator behaviour (if present) and comments explaining rationale.

B) Test change in tests/test_http_aql.cpp:

  • Update CursorPagination_SecondPage to log full response bodies for pages 1 and 2 on failure to aid debugging.
  • Add a clearer failure message when page 2 batch_size == 0 and avoid immediate hard-fail on CI by using ADD_FAILURE with diagnostic; keep primary expectations intact if non-zero.

C) PR description will reference the failing job ref: 7e043e7 for traceability.

Notes:

  • The translator change is the correct long-term fix (implementing seek-based cursor is best but larger work). This PR implements a conservative fetch-guard to make cursor pagination with ORDER BY+LIMIT behave more reliably.
  • If maintainers prefer only the translator change or only the test change, the PR can be split; this PR proposes both to get CI stable and add server-side mitigation.

Files to edit (to be discovered by the coding agent):

  • Translator/planner source(s) that set orderBy.limit (likely under src/query or src/aql or similar). Search repository for occurrences of "orderBy.limit" or where LIMIT handling is implemented.
  • tests/test_http_aql.cpp to add diagnostics and temporary defensive assertion.

Please create a branch, apply the changes, and open a pull request with this problem statement and reference the job ref in the PR description.


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI changed the title [WIP] Fix cursor pagination ORDER BY+LIMIT behaviour and make test robust Fix cursor pagination with ORDER BY returning zero items on subsequent pages Nov 3, 2025
Copilot AI requested a review from makr-code November 3, 2025 11:24
@makr-code
makr-code marked this pull request as ready for review November 3, 2025 12:23
@makr-code
makr-code merged commit 96d8924 into main Nov 5, 2025
@makr-code
makr-code deleted the copilot/fix-150588092-1085539157-63ec51c6-6e96-4b34-a99a-9b67bd231ecf branch November 30, 2025 11:50
makr-code added a commit that referenced this pull request Dec 6, 2025
…-63ec51c6-6e96-4b34-a99a-9b67bd231ecf

Fix cursor pagination with ORDER BY returning zero items on subsequent pages
Copilot AI added a commit that referenced this pull request Dec 22, 2025
… Write Buffer optimization docs

Co-authored-by: makr-code <[email protected]>
Copilot AI added a commit that referenced this pull request Jan 5, 2026
Copilot AI added a commit that referenced this pull request Jan 5, 2026
Protect iterator operations from concurrent database closure:
- Added db_lifecycle_mutex_ to guard database lifecycle
- Added active_operations_ atomic counter to track ongoing operations
- Implemented OperationGuard RAII class for safe operation scoping
- Updated scanPrefix(), scanRange(), scanAll() to use OperationGuard
- Modified close() to wait for active operations before shutting down

This prevents use-after-free crashes when close() is called while
long-running iterations are in progress.

Note: newIterator() and newAsyncIterator() methods still have lifecycle
issues as they return iterators to callers - these require API changes
or shared_ptr conversion for complete fix.

Co-authored-by: makr-code <[email protected]>
@makr-code makr-code added this to the v1.0.2 milestone Mar 11, 2026
@makr-code makr-code mentioned this pull request Mar 12, 2026
5 tasks
Copilot AI added a commit that referenced this pull request Mar 23, 2026
…ecordingCoTTracer + CoTTraceCollector (v1.7.0)

- IChainOfThoughtTracer: onStepBegin/onStepEnd noexcept + CoTSpanRecord
- RecordingCoTTracer: in-memory span store (spans/reset/toJson)
- CoTTraceCollector: fan-out tracer (addTracer/removeTracer/totalStepsTraced)
- ChainOfThoughtBuilder: attachTracer/detachTracer/hasTracer; build() fires per-step callbacks
- 30 tests, CI: cot-tracer-ci.yml
- CHANGELOG [1.7.0], ROADMAP Phase 5 item 1 done, FUTURE_ENHANCEMENTS ✅
- German docs + missing-implementations.md item #3 resolved

Co-authored-by: makr-code <[email protected]>
Agent-Logs-Url: https://github.com/makr-code/ThemisDB/sessions/285c4136-94c2-42d9-9fc4-4a5544ceda78
Copilot AI added a commit that referenced this pull request Apr 7, 2026
- TODO #1: Add idle-timeout background thread to TumblingWindow and
  SlidingWindow (idleTimeoutLoop). When no events arrive for
  idle_timeout duration the watermark is advanced to now minus
  max_out_of_orderness and expired windows are closed and emitted.
  Tracks last_event_us_ atomically; thread started only when
  idle_timeout > 0ms; stopped safely before state teardown.

- TODO #2: Store partition_key in TumblingWindow::InternalWindow and
  SlidingWindow::InternalWindow. Set on window creation from the
  creating record's partition_key. Propagate to WindowResult in
  computeResult(). Update SlidingWindow::ensureWindowsExist signature
  to accept const std::string& partition_key.

- TODO #3: Track Session::has_late_records (default false). Set to
  true whenever a late record (ev_us < wm with allow_late_data) is
  added to a session in ingest(). Pass to computeResult() in
  ingest(), flush(), and expiryLoop() so is_late_firing is correctly
  set on timer-driven and gap-triggered session closures.

- TODO #4: Add session_expiry_interval_ms to
  StreamingWindowPipeline::Config. Update session() factory to accept
  optional expiry_interval_ms parameter. Forward to
  SessionWindowConfig::session_expiry_check_interval_ms in build().

- TODO #5: Replace O(N) inner loop in SlidingWindow::ensureWindowsExist
  and HoppingWindow::ensureWindowsExist with
  unordered_set<int64_t> window_start_set_ for O(1) duplicate
  detection. Keep set in sync on window creation and pruning in
  closeExpiredWindows().

- TODO #7: SessionWindow::computeResult() now accepts bool late = false
  and sets r.is_late_firing = late. All call-sites in ingest(),
  flush(), and expiryLoop() pass s.has_late_records.

- TODO #8: RESOLVED (no code change needed) — closeExpiredWindows()
  duplicate results on shutdown.

Co-authored-by: Copilot <[email protected]>

Co-authored-by: makr-code <[email protected]>
Copilot AI added a commit that referenced this pull request Apr 13, 2026
…te gate, add CI workflow

- Add explicit add_executable(bench_policy_evaluation) to benchmarks/CMakeLists.txt.
  The file only uses a mock PolicyEngine (no real deps), so it only links
  ${BENCHMARK_LIBS} + Threads::Threads.

- Fix cmake/SuiteGating.cmake: security suite group was gated behind enterprise
  features (THEMIS_ENABLE_HSM_REAL, THEMIS_ENABLE_S3, etc.) or ENTERPRISE edition.
  Core security benchmarks (AES-GCM, RBAC, policy evaluation, audit log) rely
  only on OpenSSL + themis_core, so the gate is now unconditional (set TRUE).
  This ensures bench_security, bench_policy_evaluation,
  bench_governance_policy_latency, and bench_compliance_security_governance are
  included in themis_benchmarks_all_eligible in every build configuration.

- Update tools/perf_expectations_audit.py check #3 to also verify
  bench_policy_evaluation source + CMake target.

- Add .github/workflows/02-feature-modules_security_security-governance-benchmark-ci.yml:
  dedicated CI job that builds all four security/governance benchmark targets and
  smoke-runs them (--benchmark_min_time=0.1s). Triggers on PR/push touching
  security/governance sources, benchmarks/CMakeLists.txt, or SuiteGating.cmake.

Agent-Logs-Url: https://github.com/makr-code/ThemisDB/sessions/d6e2f482-7cef-4e7c-9aa1-4761870b3176

Co-authored-by: makr-code <[email protected]>
makr-code added a commit that referenced this pull request Apr 13, 2026
…ile (#4634)

* Initial plan

* fix(benchmarks): add bench_policy_evaluation target, fix security suite gate, add CI workflow

- Add explicit add_executable(bench_policy_evaluation) to benchmarks/CMakeLists.txt.
  The file only uses a mock PolicyEngine (no real deps), so it only links
  ${BENCHMARK_LIBS} + Threads::Threads.

- Fix cmake/SuiteGating.cmake: security suite group was gated behind enterprise
  features (THEMIS_ENABLE_HSM_REAL, THEMIS_ENABLE_S3, etc.) or ENTERPRISE edition.
  Core security benchmarks (AES-GCM, RBAC, policy evaluation, audit log) rely
  only on OpenSSL + themis_core, so the gate is now unconditional (set TRUE).
  This ensures bench_security, bench_policy_evaluation,
  bench_governance_policy_latency, and bench_compliance_security_governance are
  included in themis_benchmarks_all_eligible in every build configuration.

- Update tools/perf_expectations_audit.py check #3 to also verify
  bench_policy_evaluation source + CMake target.

- Add .github/workflows/02-feature-modules_security_security-governance-benchmark-ci.yml:
  dedicated CI job that builds all four security/governance benchmark targets and
  smoke-runs them (--benchmark_min_time=0.1s). Triggers on PR/push touching
  security/governance sources, benchmarks/CMakeLists.txt, or SuiteGating.cmake.

Agent-Logs-Url: https://github.com/makr-code/ThemisDB/sessions/d6e2f482-7cef-4e7c-9aa1-4761870b3176

Co-authored-by: makr-code <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: makr-code <[email protected]>
makr-code added a commit that referenced this pull request Apr 14, 2026
…ile (#4634)

* Initial plan

* fix(benchmarks): add bench_policy_evaluation target, fix security suite gate, add CI workflow

- Add explicit add_executable(bench_policy_evaluation) to benchmarks/CMakeLists.txt.
  The file only uses a mock PolicyEngine (no real deps), so it only links
  ${BENCHMARK_LIBS} + Threads::Threads.

- Fix cmake/SuiteGating.cmake: security suite group was gated behind enterprise
  features (THEMIS_ENABLE_HSM_REAL, THEMIS_ENABLE_S3, etc.) or ENTERPRISE edition.
  Core security benchmarks (AES-GCM, RBAC, policy evaluation, audit log) rely
  only on OpenSSL + themis_core, so the gate is now unconditional (set TRUE).
  This ensures bench_security, bench_policy_evaluation,
  bench_governance_policy_latency, and bench_compliance_security_governance are
  included in themis_benchmarks_all_eligible in every build configuration.

- Update tools/perf_expectations_audit.py check #3 to also verify
  bench_policy_evaluation source + CMake target.

- Add .github/workflows/02-feature-modules_security_security-governance-benchmark-ci.yml:
  dedicated CI job that builds all four security/governance benchmark targets and
  smoke-runs them (--benchmark_min_time=0.1s). Triggers on PR/push touching
  security/governance sources, benchmarks/CMakeLists.txt, or SuiteGating.cmake.

Agent-Logs-Url: https://github.com/makr-code/ThemisDB/sessions/d6e2f482-7cef-4e7c-9aa1-4761870b3176

Co-authored-by: makr-code <[email protected]>

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: makr-code <[email protected]>
Copilot AI added a commit that referenced this pull request Apr 19, 2026
…rce code

- analytics/README.md: add streaming_join.cpp to interface table; note
  SARIMA/PROPHET are enum-defined but not yet implemented in forecasting.cpp
- analytics/ARCHITECTURE.md: same forecasting clarification; add
  streaming_join.cpp row; update Known Limitations (AutoML/SARIMA status)
- analytics/AUDIT.md: fix test paths to tests/analytics/; update findings
  with Evidence: file:line format per AUDIT.md rules
- analytics/ROADMAP.md: correct AutoMLEngine → AutoML class name; add note
  that SARIMA/PROPHET enum values exist but switch-case handlers are missing

- prompt_engineering/ARCHITECTURE.md: add all 23 implemented components to
  Key Components table; update Known Limitations (token counting now provided
  via ContextWindowBudgetManager)
- prompt_engineering/AUDIT.md: close OI-01..OI-04 (all implemented)
- prompt_engineering/CHANGELOG.md: remove already-implemented items from
  Unreleased; merge duplicate [2.0.0] header into single release block
- prompt_engineering/SECURITY.md: update Supported Versions (2.0.x active);
  correct KL-01 (ContextWindowBudgetManager exists; approximation noted)

- rpc_grpc/README.md: update version 0.0.1 → 0.2.0; add BidiStreamAdapter
  to Component Table
- rpc_grpc/ARCHITECTURE.md: update version/date; add BidiStreamAdapter class
  row; fix Known Limitations (uptime tracking done; reloadTls implemented)
- rpc_grpc/SECURITY.md: fix GRPC-SEC-01 (hot-reload IS implemented in v0.2.0;
  only existing-session renegotiation is by-design limitation)
- rpc_grpc/FUTURE_ENHANCEMENTS.md: mark BidiStreamAdapter (#3) and TLS
  Hot-Reload (#4) as ✅ Implemented (v0.2.0)
- src/rpc_grpc/grpc_plugin.cpp: fix getVersion() return value from "1.0.0"
  to "2.0.0" to match CHANGELOG v0.2.0 entry and test expectation

Co-authored-by: Copilot <[email protected]>

Co-authored-by: makr-code <[email protected]>
makr-code added a commit that referenced this pull request Jul 16, 2026
…ld-strategy

[EPIC #3] Define recovery, rebuild, and erasure strategy for distributed tensor artifacts
makr-code added a commit that referenced this pull request Jul 17, 2026
…rk-implications

[EPIC #3] Hardware & network assessment for distributed tensor artifact fabric
Copilot AI added a commit that referenced this pull request Aug 15, 2026
Add comprehensive test suite for Phase 5 C++ safety fixes:

1. test_index_destructor_safety.cpp (338 lines, 10 tests)
   - VectorIndexManager destructor exception handling
   - GPUVectorIndex destructor exception safety
   - Noexcept verification (static_assert)
   - HNSW resource cleanup validation
   - Tests: destructor no-throw, exception during shutdown, stack unwinding,
     multiple calls, concurrent destruction, GPU variants

2. test_index_iterator_validity.cpp (411 lines, 10 tests)
   - Snapshot pattern validation for iterator safety
   - Partition removal stress tests (500+ partitions)
   - Concurrent add/remove patterns (TSan validation)
   - Data operations concurrent with partition removal
   - Tests: safe removal, stress, concurrent access, interleaved patterns,
     snapshot semantics, edge cases (empty, duplicates)

3. test_index_gpu_memory_safety.cpp (458 lines, 10 tests)
   - GPU resource allocation/deallocation pairing (RAII)
   - Memory leak detection across init/destroy cycles
   - Exception safety during GPU initialization
   - Large allocation handling near GPU memory limits
   - Tests: basic allocation, leak detection, exception cleanup, large allocations,
     concurrent management, explicit shutdown, idempotency, state validation

CMakeLists.txt Updates:
- Auto-discovery of test_index_*.cpp files preserved
- Conditional CUDA linkage for GPU tests when THEMIS_CUDA_ENABLED=ON
- Proper test registration via themis_register_module_focused_test()

Validation Coverage:
✓ 30 comprehensive tests (10 per test file)
✓ Exception safety (try/catch scenarios)
✓ RAII patterns (noexcept destructors)
✓ Memory safety (allocation/deallocation tracking)
✓ Concurrency (TSan-compatible multi-threaded tests)
✓ Edge cases (empty, large scale, duplicate operations)
✓ Timeout: 120s per test (reasonable for Phase 5 workloads)

Build Integration:
- Compile: cmake --build . -j 16 (automatically discovered)
- Run: ctest -R "test_index_(destructor|iterator|gpu)" --output-on-failure
- Sanitizers: Built-in support for ASan/TSan/UBSan
- No additional dependencies beyond existing test infrastructure

Fixes Phase 5 Blocker #6 (MEDIUM) by providing regression test coverage
for fixes #1-4:
  Fix #1: VectorIndexManager::~VectorIndexManager() noexcept (line 94)
  Fix #2: releaseHnswResources_() helper for safe cleanup (line 304)
  Fix #3: GPUVectorIndex::~GPUVectorIndex() noexcept (line 121)
  Fix #4: Iterator invalidation fix via snapshot pattern (line 107)

All tests are production-ready and CI/CD compatible.

Co-authored-by: makr-code <[email protected]>
Copilot AI added a commit that referenced this pull request Aug 17, 2026
…critical gate, integrate SRG benchmarks

BLOCKER_FIX_1: Add release_critical label to SCR-01..16 tests
  - File: tests/sharding/CMakeLists.txt:421
  - Enables fail-closed verification in Wave A gate

BLOCKER_FIX_2: Add Wave A Release-Critical CI verification step
  - File: .github/workflows/ci-build.yml (new step after main ctest)
  - Runs 108 release_critical tests (TXC/FLR/FI/SCR suites)
  - Expected runtime: ~5-10 min
  - Verifies Wave A exit criterion #3

BLOCKER_FIX_3: Integrate SRG-01..06 benchmarks in CI pipeline
  - File: .github/workflows/ci-benchmarks.yml (new sharding-release-gates job)
  - Runs all 6 Wave A baseline benchmarks
  - Validates p95/p99 against thresholds
  - Expected runtime: ~20-30 min
  - Verifies Wave A exit criterion #4

All fixes ready for immediate deployment to develop branch.

Co-authored-by: makr-code <[email protected]>
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.

2 participants