Bug #12020
Replace AdaptiveQuery dynamic mode with PagedResults
50%
History
#1 Updated by Alexandru Lungu about 1 month ago
- Assignee set to Alexandru Lungu
This task is about a proposal to replace the invalidation of AdaptiveQuery.
Today:
- preselect mode of AQ is using a
ProgressiveResultsto gather rows in increasingly larger brackets - if a change in the walked index occurs, the AQ will delegate a RAQ to retrieve records one by one (using the FIND NEXT implementation)
- if the value of the column that occurs first in the index is different than the baseline, then the AQ is revalidated and a
f1 > <break-value>is used.
The issues of this implementation is that:
- dynamic mode always requires rows one by one.
- revalidation may never occur (e.g.
where f1 = 2025 and (f1 = 2025 and f2 > ?)). The sort-band in question (i.e.f1 = 2025) can refer to thousand of records. This is a customer example that iterates all records operated in a certain year. It revalidates only when the year is changed, but this never happens as the WHERE clause enforces a specific where- disclaimer, this specific case is optimized through fqlpreprocessor and we can revalidate on the second component of the index if the first component is fixed in WHERE. However, this happens only if the WHERE clause is trivial (conjunction of equalities, so no functions, or operators, etc.).
ProgressiveResultsis a performance bomb. Once the i-th bracket is reached, the query emitted has LIMIT N OFFSET M. That M of the offset is the number of rows skipped from the beginning of the index/table. Thus, the query iterates each row a logarithmic number of times.ProgressiveResultsare hard to invalidate due to cross-session changes. The only guardrail we have is that the last record in a bracket should match the first record of the next bracket. However, it doesn't pro-activelly invalidate if a cross-session change occurs while still iterating the bracket.- If another session inserts a record right at the beginning, the
ProgressiveResultswill simply invalidate because the offsets won't match anymore. However, that newly inserted record wasn't going to affect the results that were still to be traversed. This happens because at the offset checking time, we don't have much feedback on how the new/updated/deleted rows affected the index.
- If another session inserts a record right at the beginning, the
My suggestion:
- The
PagedResultsis a parallel implementation very similar toProgressiveResults, but it uses a reference row instead of an OFFSET. Thus, instead of emitting LIMIT N OFFSET M to skip the first M rows, it emits WHERE .... AND (<indexed-fields> > <reference-indexed-fields) LIMIT N. The additional clause (fql bundle) is made out of several statements, based on index size. Due to null augmentation, some of the fqls also havef1 > ? or f1 is null.- This is only used in NO-LOCK, forward-only or iterating FOR EACH queries in TCP/IP connection mode to emulate prefetching.
- Current implementation uses BASE 16 and progressivelly increments it.
- It resets the page size back to 16 if another session commits, being proactivelly in invalidating and seeing only the records meant to be seen by the query.
- Shared-memory database can use
PagedResultswith BASE set to 1.- It will work as
ProgressiveResultsunder no cross-session invalidation. - It will work as an automatically revalidated query after cross-session invalidation (i.e. reset bracket size to 1).
- There is no point in distinguishing cross-session commits and intra-session flushes, thus there is no point is pro-activelly invalidating and using a RAQ when the same session commits.
- It will work as
- The AQ should still invalidate to RAQ in order to leverage the dirty-share implementation. For the moment, we can distinguish intra-session invalidation due to physical DB update or dirty-share update.
- in case the change is flushed to the db, it is fine just to reset the
PagedResultsbracket size back to 1. - in case the change was put in dirty-share, then we really need to invalidate.
- this second technical dept will be mitigated by #8388, because we will be able to pick dirty-changes directly from the DB using
PagedResults.
- this second technical dept will be mitigated by #8388, because we will be able to pick dirty-changes directly from the DB using
- in case the change is flushed to the db, it is fine just to reset the
End-game:
- All FOR EACH queries will use
PagedResultsand will simply reset the bracket size to BASE:- BASE is 1 in shared-memory DB
- BASE is 16 (or computed from -MM) in TCP/IP DB
Performance:
- The
PagedResultshas slower plans, but faster invalidated modes, both intra- and cross-. - The
ProgressiveResultshas faster plans for small result-sets, but slower in larger result-sets and invalidated modes, both intra- and cross-. - I think the cross-session invalidation on
PagedResultscan be improved by not invalidating on any foreign commit, but only on foreign commits that touch the target tables. This is not implemented because of the machinery required (needing to monitor what tables were affected in a foreign commit). - I think the OR bundled will be eventually optimized by the effort in #11980
Please provide feedback
#3 Updated by Alexandru Lungu 25 days ago
- Assignee changed from Alexandru Lungu to Artur Școlnic
Artur, please explore this idea.
#4 Updated by Artur Școlnic 25 days ago
- Status changed from New to WIP
#5 Updated by Artur Școlnic 24 days ago
I prototyped the proposal (temporary trunk patch, since removed): when AdaptiveQuery goes into dynamic mode on a paging-eligible single-table NO-LOCK walk, it continues with a PagedResults anchored after the current row (the pre-change copy if the walk moved its own row) instead of a RAQ; a later own change drops the page and re-anchors. Compared against trunk and against OpenEdge 12.8 client/server over TCP (-H localhost -S 20991 -Mm 1024, default prefetch).
Walk: FOR EACH dsNonunique WHERE si1 = "PW" NO-LOCK (si1 pinned, as in the customer case). All runs repeated 2-3 times with identical results.
Cost, 20000 rows; "dynamic" = the walk changes an index field of another row on its first row:
| Walk | trunk (RAQ dynamic) | paged dynamic, page 16 | paged dynamic, frozen page 64 |
|---|---|---|---|
| dynamic mode, quiet | 69-115 s | 58-127 ms | 3.0-3.2 s |
| dynamic mode, another session committing to an unrelated table | 71-74 s | 5.1-5.3 s | 3.1-3.3 s |
| preselect, quiet | 138-208 ms | 55-212 ms | 3.0-3.3 s |
| preselect, another session committing | 71-103 ms | 5.2-5.8 s | 3.0-3.5 s |
- Own changes (create/delete/update/move ahead and behind, move of the current row, inside an outer transaction): paged dynamic mode gives the same rows as the RAQ in all 10 scenarios.
- Foreign commits while paused: OE over TCP froze the whole 60-row remainder (one prefetched message). Trunk and paged page 16 are fresher than OE (they see a change to row 40). A frozen 64-row page matches OE there, but misses rows appended past the end, because it takes a short page (60 < 64) as the end of the walk where OE asks the server once more.
- Replacing the RAQ with
PagedResultsis the big win: ~1000x on a long walk, same results on own changes. - Shrinking the page on any foreign commit should go: it does not match OE over TCP (which ignores commits inside its window) and costs ~5 s per 20000 rows under load, because
foreignCommitCount()is per database. - Candidate design: first page frozen at
-prefetchNumRecs(OE parity), geometric growth after it, no shrinking, and one extra query on a short page before ending the walk. - The "flushed: reset the page, dirty only: invalidate" rule cannot be keyed off
AdaptiveQuery.stateChanged: same-session updates and inserts arrive there before they are flushed. Re-anchoring at the next page open, as in the prototype, avoids that. - Still RAQ: locked walks, joins, client-side WHERE (not paging-eligible). Shared memory not measured, I believe it is not 'in scope' at all here.
Alex, please review the summary of the design below.
Design: PagedResults as AdaptiveQuery's dynamic mode
When a forward NO-LOCK walk is invalidated by a change made in its own session, continue it with reference-row pages instead of a RAQ. Match OpenEdge client/server (TCP) where measured, and do not slow down when other sessions commit.
Why (20000-row walk, FWD trunk):- Dynamic mode today (RAQ, one
FIND NEXTper row): 69-115 s. Preselect: 0.1-0.2 s. - The prototype (paged dynamic mode): 58-127 ms, same rows as the RAQ in all 10 same-session scenarios.
- OE over TCP (
-Mm 1024) delivered the whole remainder of a 60-row walk from its prefetched message: commits by other sessions inside that window were not seen.
Scope: queries AdaptiveQuery.pagedResultsConfig() already accepts (one table, NO-LOCK, forward-only or iterating, no client-side WHERE, no external buffers, no join). Locked walks, joins and client-side WHERE keep the RAQ. Shared-memory databases are not changed until measured.
- First page:
Wrows,W=prefetch-num-recs(legacy-prefetchNumRecs), default 64 for 12.x (to be confirmed on OE). - Later pages grow geometrically from
W, up to the existing memory cap. - No shrinking or cutting a page because another session committed: remove
capPageOnForeignCommitand the reset inresizePage. Today this costs 5-6 s per 20000 rows under load and does not match OE. - A short page does not end the walk: run the cascade once more from the last row; only an empty result ends it. Without this, a 64-row page missed rows appended past the end, which OE delivered.
- On a same-session invalidation, create a
PagedResultsinstead of the RAQ (createSimpleQuery). - Anchor it after the walk's current row; if the change modified that row, anchor on the event's pre-change snapshot, so the walk continues from the old key.
- Later same-session changes drop the current page and re-anchor; the next page is read after the flush, on the same connection.
- No "flushed vs dirty" decision in
stateChanged: updates and inserts arrive there before they are flushed. - No break-value revalidation for these queries: paged dynamic mode costs the same as preselect.
| Class | Change |
|---|---|
AdaptiveQuery |
execute() builds PagedResults instead of DynamicResults/RAQ for eligible queries; stateChanged() keeps the anchor and calls dropPage(anchor) in paged dynamic mode. |
PagedResults |
anchorAfter(Record), dropPage(Record); first page W thoreign commits; short page re-queries once. |
PagedResultsConfig |
prefetch-num-recs default 64. |
Persistence |
foreignCommitCount() no longer used by paging. |
Validation: tests/concurrency/paged_walk (10 foreign-commit scenarios) an_change@ (10 own-change scenarios) on FWD and OE over TCP, plus@tests/concurrency/paged_walk_bench@. Confirm W on OE with a 200-row seed and a pause after row 70.
- OE over TCP does not show its own inserts or key moves inside the current does today).
- Pages after the first are wider than OE's
W-row messages, so deep in a walk FWD can be staler than OE. Not measured on OE; keeping every page atWcosts ~3 s per 20000 rows instead of ~0.1 s. - Dirty share was not exercised by any scenario.
#6 Updated by Alexandru Lungu 24 days ago
When a forward NO-LOCK walk is invalidated by a change made in its own session, continue it with reference-row pages instead of a RAQ. Match OpenEdge client/server (TCP) where measured, and do not slow down when other sessions commit.
This is the design, indeed. But the tough nut here is the dirty-share. We can't abandon it under no circumstances.
Candidate design: first page frozen at -prefetchNumRecs (OE parity), geometric growth after it, no shrinking, and one extra query on a short page before ending the walk.
Mind that this is the marginal case of using TCP/IP. The first and foremost line of development here is shared memory used by most customers. Supporting shared memory is more faithful than TCP/IP than vice-versa (a customer using a legacy TCP/IP connection is more lenient with FWD in shared memory than legacy shared memory using TCP/IP in FWD). This is why I want a shared memory first analysis.
No shrinking or cutting a page because another session committed: remove capPageOnForeignCommit and the reset in resizePage. Today this costs 5-6 s per 20000 rows under load and does not match OE.
I don't understand this. Why would we remove this ... wouldn't it functionally mismatch OE? If the page progressively increased to a 64.000 sized page and the cursor is still in the first half of the page, it will take another 32k records to iterate to see the committed changes of another session. In OE, they are visible after at most 64 iterations. That is why we shrink the page back when another session committed.
A short page does not end the walk: run the cascade once more from the last row; only an empty result ends it. Without this, a 64-row page missed rows appended past the end, which OE delivered.
Reasonable!
OE over TCP does not show its own inserts or key moves inside the current does today).
I think this can be easily fixed. Instead of the foreign commit counter, we will drive the same-session changes (stateChanged) so simply invalidate the PagedResults just like foreign commit does.
Pages after the first are wider than OE's W-row messages, so deep in a walk FWD can be staler than OE. Not measured on OE; keeping every page at W costs ~3 s per 20000 rows instead of ~0.1 s.
Are wider to improve performance, but do not affect functionality. Any foreign commit will bounce back the page to the BASE size (currently defaults to 16). I agree that OE doesn't get results in incrementally larger page, but FWD will trim the large page on the first invalidation, so it will "emulate" single sized pages. As long as the batch size is not fully deterministic (at least in FWD we don't compute the actual page size dynamically), there is an epsilon to be considered (i.e. there might be a couple of rows more or less in the window of FWD than OE; this invariant allows us to use incremental pages and bounce back to 16).
Dirty share was not exercised by any scenario.
#8388 is a prerequisite of this task. PagedResults shall be emitted with UNION ALL just like RAQ does in #8388. This way, we never invalidate, but rather send complex queries once an invalidation occurs. As we progress further, the active bundle will get less and less complex - re-validating implicitly.
I think there are multiple phases for this task that will be adopted in trunk one-by-one:
Implementation of a per-table foreign commit counter¶
We need a powerful and safe foreign commit counter in the FWD server. We need to create this mechanism and test the hell out of it.
The effort from 10806a and #10222 will be wrapped-up in one single powerful ForeginCommitCounter class that will handle this mechanism (or something similar to this.
- replace the
PagedResultsforeign commit counter with the per-table one and merge it like that. - leverage it to fix #10222 and invalidate FFC
- we need to assess cluster mode very carefully to check if it is scalable.
- we need to test multi-tenancy and ensure foreign commit are broadcast correctly intra-tenant in private vs shared mode
- we need to do memory leak tests to ensure that every one commit will accumulate some state in the FWD server.
Goal: we implement the per-table foreign commit counter mechanism, test functionality/performance/ memory and merge to trunk.
PS: Mind that we already have the global events that are broadcast cross-session. This was used in dirty-share, but afaik it is completely disabled in most/all environments. Lets see if we either leverage that or purge that. I don't want both such events being broadcasted and a separate foreign commit mechanism in place. If we need to keep the global events only for cross-session dirty-share, so be it. Lets document it that way and keep it as such.
Make AdaptiveQuery sensitive to other session commits¶
- preferably #10806 will be done by this time
This is basically integrating the foreign commit logic in AQ invalidation. At this time, RAQ is used and not PagedResults.
We need to test the hell out of this before moving on with PagedResults optimization for forward-only. We need to ensure that functionally the AQ invalidation will work as in OE in terms of multiple session committing at the same time.
Switch RAQ for PagedResults¶
- #8388 should be ready
- #11980 should be ready
This is the core logic of this task as you described previously. I am trying to think if we can split this as well to separate PagedResults logic from dirty-share ... I guess not. When we will reach this point, we will do some brainstorm to identify the right scope.
Make PagedResults available to non-forward only¶
PagedResults implementation does not depend on moving only forward. As long as we have a reference row, we can always emit the query with reversed order by and gather the results in the other way around. In fact, this will make reverse iterations faster than trunk which doesn't invalidate. Trunk with PREV is ruling out the re-validation bets completely.
#7 Updated by Artur Școlnic 21 days ago
Agreed on the phases, shared memory first, #8388 as prerequisite and the page epsilon.
- Shrinking on foreign commits: you are right, we keep it. My point came from a 60-row walk over TCP, where the whole set fits in one message. The 5-6 s cost I measured came from commits to an unrelated table, so the per-table counter is what removes it.
- Own inserts/moves: the quoted line was truncated; it should read "OE over TCP does not show its own inserts or key moves inside the current window; FWD does (as the RAQ does today)". So FWD is fresher than OE TCP there, and invalidating
PagedResultsfromstateChangedkeeps that behaviour, which is most likely the shared-memory one. I will confirm with the shared-memory run. - Global events: I will cover leverage vs purge in the phase 1 inventory.
#8 Updated by Artur Școlnic 11 days ago
- Status changed from WIP to Review
- reviewer Alexandru Lungu added
12020a contains changes according to #10275-159.
Preliminary regression testing results:| Suite | Tests | trunk (pass / fail) | 12020a (pass / fail) |
|---|---|---|---|
| tests/concurrency/paged_walk | 20 | 16 / 4 | 16 / 4 |
| tests/persistence/walk_own_change | 10 | 10 / 0 | 10 / 0 |
| tests/concurrency/paged_walk_bench | 24 | 24 / 0 | 24 / 0 |
| Total | 54 | 50 / 4 | 50 / 4 |
| Paging | Jar | Walk alone, ms (median, range) | Walk while the other session commits, ms (median, range) | Slowdown | Commits/s (run 1, run 2) |
|---|---|---|---|---|---|
| off | trunk | 100 (50-236) | 114 (62-188) | 1.1x | 270, 930 |
| off | 12020a | 103 (44-195) | 111 (64-170) | 1.1x | 300, 770 |
| on, page 16 | trunk | 96 (90-231) | 4916 (4805-5858) | 51x | 1270, 1330 |
| on, page 16 | 12020a | 163 (97-298) | 182 (126-304) | 1.1x | 290, 380 |
| on, page 256 | trunk | 107 (87-234) | 504 (384-676) | 4.7x | 660, 680 |
| on, page 256 | 12020a | 124 (100-304) | 175 (149-256) | 1.4x | 290, 390 |
One session walks 20000 rows with a NO-LOCK FOR EACH dsNonunique WHERE si1 = "BM" while another session commits to dsUnique (one-row transactions, as fast as it can). Each cell is 2 runs x 3 walks on PostgreSQL.
Will run more testcases routines, including multi session.
Alex, please review 12020a.
#10 Updated by Artur Școlnic 11 days ago
More testing results
| Suite | Tests | trunk (pass / fail) | 12020a (pass / fail) |
|---|---|---|---|
| tests/concurrency/paged_walk | 20 | 16 / 4 | 16 / 4 |
| tests/persistence/walk_own_change | 10 | 10 / 0 | 10 / 0 |
| tests/concurrency/paged_walk_bench | 24 | 24 / 0 | 24 / 0 |
| tests/query/adaptive/progressive_results/changes_during_walk | 123 | 109 / 14 | 109 / 14 |
| tests/query/adaptive/progressive_results/commits_inside_walk | 132 | 110 / 22 | 110 / 22 |
| tests/query/adaptive/progressive_results/walk_delivery_across_brackets | 129 | 118 / 11 | 118 / 11 |
| tests/query/adaptive/commit_transaction_and_session_boundaries | 159 | 149 / 10 | 149 / 10 |
| tests/query/adaptive/unflushed_records_and_dirty_share | 147 | 140 / 7 | 140 / 7 |
| tests/concurrency/break_by_foreign_commit | 18 | 18 / 0 | 18 / 0 |
| tests/concurrency/fast_find_commit_window | 8 | 7 / 1 | 7 / 1 |
| tests/concurrency/fast_find_isolation | 24 | 18 / 6 | 18 / 6 |
| tests/concurrency/get_current_lock | 20 | 14 / 6 | 14 / 6 |
| tests/concurrency/indexed_reposition | 26 | 16 / 10 | 16 / 10 |
| tests/concurrency/indexed_reposition_browsed | 24 | 0 / 24 | 0 / 24 |
| tests/concurrency/other_session_dirty_visibility | 10 | 7 / 3 | 7 / 3 |
| tests/persistence/flushing_validation | 163 | 7 / 156 | 7 / 156 |
| tests/persistence/failed_assign_undo | 86 | 28 / 58 | 28 / 58 |
| tests/persistence/dirty/unique_find | 59 | 57 / 2 | 57 / 2 |
| Total | 1182 | 848 / 334 | 848 / 334 |
#11 Updated by Artur Școlnic 10 days ago
- % Done changed from 0 to 100
Regression tested 12020a with customer projects.
The multi tenant app, large gui app unit tests, chui regression and etf passed.
If the review is positive, we can merge.
#12 Updated by Alexandru Lungu 10 days ago
I will do this somewhere in the next 2 hours. Stay tuned!
#13 Updated by Alexandru Lungu 10 days ago
- % Done changed from 100 to 80
- Status changed from Review to WIP
Review of #12020:
- I don't get a grip on
UNKNOWN_TABLE. This seems like a marker for "commit on all tables", but why would this be needed? This looks like a signal to invalidate all queries, but I would like to figure out why this would ever happen as it may look disastrous. - Is this implementation making a distinction in between tenants? If tenant A commits on logical table X, does tenant B queries over logical table X invalidate? It looks like such.
- This happens at least for private database I guess, while shared does allow cross-tenant invalidation.
- Please double-check the how this behaves in a clustered environment. I guess we really need to broad-cast the commit in between servers. Please confirm.
AdaptiveComponent comp = (AdaptiveComponent) components().get(0); RecordBuffer buffer = comp.getBuffer();looks fishy. Are we using
PagedResults only for single-table queries? If so, I guess we will need to extend logic in #12020 to allow multi-table queries to be fetched using PagedResults.
- I think we would need a more tight lock on
commitCounters. There are some time-frames in which we can update only X% of the foreign commits on the tables and a reader may see that x% of the tables were committed to while 100-X% of them were not yet updated. I would plan for a ReadWriteReentrantLock instead of nestedConcurrentMap. Lower these to normal maps and make access to this nested structure using theReadWriteReentrantLock. For instance:
for (Map.Entry<Database, ConcurrentMap<String, AtomicLong>> e : commitCounters.entrySet())
may be concurrently updated. While commitCounter is an AtomicLong, there are time-frames in which the commits apply partially. This is against ACID, as one session can see partial commits and these are not even atomic (an error can eventually leave the collection stale). I would prefer to have a sound implementation that lay grounds for multi-table query support here, so reads on N tables, updates on M tables concurrently.
- The
commitCounterseries of API can be moved in an inner static class to contain the logic for this architecture. I don't enjoy seeing it spread inPersistence. Or better, we can move it in a separate class altogether. There can be one suchForeignCommitTrackerper physical database.
Lets take the time to fine tune this mechanism. For #10275 there is an workaround in place, so there is no urgency to motivate a partial solution now.
#14 Updated by Artur Școlnic 10 days ago
- % Done changed from 80 to 100
UNKNOWN_TABLE: not "invalidate all queries" - eachPagedResultswalk on that database drops back to page 16 once, which trunk does today on every commit. Sources:Session.bulkCopy()(onlyImportWorker, table known by SQL name only - I will map it to the DMO and remove this case) andCommitNotice.missed()(cluster: a server that missed or failed to apply a notice cannot know the tables; it already clears the whole FastFindCache).- Tenants: counters are keyed by the context's
Database; a multi-tenant table resolves to the tenant's private database, so tenant A's commit to X does not reset tenant B's walks over X. Shared-database tables count for all tenants, as the rows are shared. Not tested yet - adding a two-tenant scenario. - Cluster: yes, broadcast. The existing
CommitNoticecarries the DMO class of each changed record; the receiver now counts per table. Only sent for primary databases with versioning and a cluster key. Not run in a cluster yet. - Single table: yes,
pagedResultsConfig()rejectsgetTableCount() != 1. Multi-table paging is a later step. - Atomicity: agreed. A commit's tables are published one at a time; for today's single-table walks that only delays the reset by one sample, but multi-table readers need it atomic. I will publish under a per-database write lock and give readers a consistent snapshot - the count is sampled on every row, so I will compare
StampedLockoptimistic reads withReentrantReadWriteLockinpaged_walk_bench. - Found while re-checking: a direct
Session.commit()outsideContext.commit(RecordNursery, no open transaction) is claimed as own only at the next context commit, so the walk's count can go up and back down and hide a foreign commit in between (stale page, not wrong rows). Fix: claim own commits when they are published. - Separate class: agreed -
ForeignCommitTracker, one per physical database.
Next: tracker + the two fixes above, unit tests under concurrency, two-tenant test, two-server cluster test (incl. missed()), long-run memory check, then the regression suites and the benchmark again vs trunk.
#15 Updated by Artur Școlnic 7 days ago
- % Done changed from 100 to 80
#16 Updated by Artur Școlnic 7 days ago
Committed rev 16845.
- New ForeignCommitTracker, one per physical database: a commit's tables and the committing context's own counts are published together under one lock. A paged walk therefore never sees part of a commit, and never sees its own commit as foreign.
- Fixed a late own-commit claim: each Session now carries its context's owner, so a direct commit counts as own straight away.
- Imports name their table: bulk copy passes its DMO, so imports no longer count as an unknown table.
- Database matching and lifecycle: cluster notices are matched by database type and name. Only primary databases are tracked, and a tracker is dropped when its database is deregistered or a tenant database is removed.
- Lock: StampedLock with optimistic reads. A read costs 4–7 ns, against ~1.4 µs for a ReentrantReadWriteLock with 8 readers.
- Tests: 15 new unit tests, all passing. The concurrency tests fail on the old table-by-table publishing, so they do catch it.
- FWD runs (1155 tests): results match trunk and r16844 apart from the known flaky test.
- Performance: commits to unrelated tables no longer slow a paged walk (page 16: trunk 56×, now 1.0×).
- Memory: no growth per commit.
Will do the tenant and clustering testing next.
#17 Updated by Artur Școlnic 6 days ago
- Status changed from WIP to Review
Artur Școlnic wrote:
Will do the tenant and clustering testing next.
Eduard tested them, all passed.
#18 Updated by Alexandru Lungu 5 days ago
- Status changed from Review to Internal Test
Review of 12020a. The changes are GOOD!
Only one AI finding:
DatabaseManager.deregisterDatabase: ForeignCommitTracker.discard runs after configLock is released. If a context reconnects the same transient database in that gap, its session keeps an owner from the tracker that is about to be discarded. Until that session closes:
- walks opened before the discard stop seeing other sessions' commits;
- the context's own commits count as foreign commits in walks it opens later.
TenantManager tenant-database removal has the same race but is less likely to hit it. Possible fixes:
- run the discard under
configLocktogether with the ref-count check; or - have
Session.publishWriteslook up its owner from the context at commit time instead of keeping the one it got at creation.
- please rename methods as verbs. E.g.
ForeignCommitTracker.Owner owner = commitOwner();togetCommitOwner
Given the review requests slim and safe changes, please continue with testing.
#19 Updated by Artur Școlnic 4 days ago
- % Done changed from 80 to 100
Multi tenant app, large gui app unit tests, chui regression and etf passed.
I am running some latency testing now, ETA 1h, if it also passes, we can merge.
#20 Updated by Alexandru Lungu 4 days ago
I am running some latency testing now, ETA 1h, if it also passes, we can merge.
Please have:
- a functional harness to capture the changes in here. Tell AI to design it and commit it to testcases.
- a load testing harness that also captures performance. Have maybe 10 sessions do a scenario that exploits this (commit on either table A or B or query A or B). Cross check OE vs trunk vs 12020a.
- an AI test with cluster and multi-tenant set-up that does exactly what bullet 2 does.
- confirm that separate tenants do not affect each other.
- confirm that clusters broadcast the foreign commit correctly and fast. Analyze performance of cluster broadcast of foreign commits. Eduard, please help with this analysis or the way to set it up and validate it doesn't bring more contention the cluster. This is critical.
#21 Updated by Alexandru Lungu 4 days ago
Some post thought on the last review assessment:
- Session.writtenEntities should be final.
- Session.noteWrite should be private and moved into the private-methods block.
#22 Updated by Alexandru Lungu 4 days ago
FYI, I delivered some slim local tests my own and I am confident with the current shape of changes. Artur, please let me know when #12020-20 results come in on your side. If everything is set, up and running correctly, we are only left with merging.
#23 Updated by Artur Școlnic 4 days ago
Cluster tests are taking a while, eta 30 minutes, no issues so far.
#24 Updated by Artur Școlnic 4 days ago
Testing plan of #12020-20 is done. No regression of 12020a found. trunk below is r16843 (12020a without its commits); paging is legacy-remote with page 16; FWD runs on PostgreSQL, OE 12.8 on shared memory.
1. Functional: tests/concurrency/foreign_commit_per_table
10 scenarios: a paused NO-LOCK walk of table A while another session commits to A, B, both, B then A, or rolls back. OE, trunk and 12020a pass 10/10, three times each, on one server and with writer and reader on different cluster servers.
2. Load: tests/concurrency/foreign_commit_load
10 sessions walking or committing to tables A/B. Median time per 20000-row walk:
| Scenario | OE | trunk | 12020a |
|---|---|---|---|
| walk A, commit B | 69 ms | 8371 ms | 146 ms |
| walk A, commit A | 105 ms | 8284 ms | 8237 ms |
Commit throughput is the same on trunk and 12020a.
3. Multi-tenant and cluster
- Multi-tenant: commits in tenant t1 no longer slow walks in t2 (trunk 3484 ms, 12020a 101 ms). No cross-tenant leak.
- Cluster (2 servers, 2 Geode locators, one host): commits on server 1 reach walks on server 2 correctly, and commits to other tables no longer slow them (trunk 8128 ms, 12020a 129 ms).
- Contention: the synchronous commit notice halves commit throughput on 2 servers, on trunk and 12020a alike (e.g. 3188-3455/s on one server, 1577-1797/s on two). This is the #4369 design, not 12020a.
Findings, not caused by 12020a
- Commits to the walked table keep the page at 16 rows, making paged walks ~80x slower than OE or paging off.
- With paging off, FWD misses committed updates deep in a walk where OE does not.
#25 Updated by Alexandru Lungu 4 days ago
- Status changed from Internal Test to Merge Pending
Assess #12020-21, if not already. Afterwards, please merge 12020a to trunk.
#28 Updated by Artur Școlnic 4 days ago
- Status changed from Merge Pending to Test
12020a was merged to trunk/16860.
#29 Updated by Artur Școlnic 4 days ago
Added tests/concurrency/foreign_commit_per_table to testcases.
#30 Updated by Alexandru Lungu 4 days ago
- Status changed from Test to WIP
- % Done changed from 100 to 50
This task is broader; I will return it to 50% / WIP to pursue our goal of leveraging PagedResults in more places than today.
#31 Updated by Daniel Mocsi 4 days ago
Hi, it seems like the remaining performance problems at the customer mentioned in #12120 are related to the queries that get split into multiple SELECT ... LIMIT ... OFFSET queries, when the OFFSET becomes very large. When the changes from this ticket are ready, could you make some time measurements for queries that return 100k-1M+ rows? We could also test a patch with these changes on the customer test environment with real data.
#32 Updated by Alexandru Lungu 3 days ago
- Priority changed from Normal to High
Daniel Mocsi wrote:
Hi, it seems like the remaining performance problems at the customer mentioned in #12120 are related to the queries that get split into multiple
SELECT ... LIMIT ... OFFSETqueries, when the OFFSET becomes very large.
Daniel, thank you for your attention on this task.
First and foremost, the 12020a branch that we just merged fixes a performance regression of legacy-remote connection option (for whose support we just committed to a couple of weeks ago and it is in trunk now). This option is to be used by customers that connected their DB using TCP/IP, because it behaves functionally different, i.e. the PREFETCH feature is enabled. With shared-memory connection, there is no PREFETCH, so it is unsafe to toggle legacy-remote. Of course, this can be decided per-customer basis if they want to have their DB running with prefetch like a legacy OE TCP/IP connected DB, but it has its own risks (e.g. not being able to see committed rows from other transactions in real-time, but only after the prefetched batch is iterated), but also benefits (it is faster).
refs: #11723 and you can read about the option in Database Tuning wiki.
Secondly, this task as a whole is to leverage thePagedResults implementation (i.e. that relies on reference rows - idx-field > ?, rather than OFFSET) that we used for this legacy-remote even for shared memory. Today:
- shared memory legacy connected DBs use
ProgressiveResultsthat use OFFSET for their queries - some queries in
legacy-remoteconnected DBs usePagedResultsthat useidx-field > ?
I expect we will make progress in this direction in the upcoming weeks.
So, Artur, lets increase the priority of this task and do baby steps into delivering new support for shared-memory connected DBs to the speed of the PREFETCHing technique.
When the changes from this ticket are ready, could you make some time measurements for queries that return 100k-1M+ rows? We could also test a patch with these changes on the customer test environment with real data.
Artur, can you deliver in this task just as a sneak-peak of the times on the customer using today legacy-remote?
#33 Updated by Artur Școlnic 3 days ago
- Priority changed from High to Normal
I benchmarked a test case, trunk r16860, PostgreSQL, one session, no concurrent commits: FOR EACH dsNonunique WHERE si1 = ... NO-LOCK, median of 3 walks.
| Rows | Paging off (ProgressiveResults) | legacy-remote page 16 | legacy-remote page 256 |
|---|---|---|---|
| 10k | 103 ms | 128 ms | 108 ms |
| 100k | 218 ms | 312 ms | 284 ms |
| 1M | 2641 ms | 4772 ms | 2265 ms |
legacy-remote does not speed up large walks yet. PagedResults positions each page with (upper(rtrim(si2)) > ? or upper(rtrim(si2)) is null); the OR IS NULL makes PostgreSQL filter instead of seek, so every page re-reads the band from its start, as OFFSET does. A 1000-row page at row 900k: OFFSET 208 ms, PagedResults 244 ms, the same query without OR IS NULL 0.37 ms. That rewrite (#11980) is what makes reference rows pay off.
Will check the customer scenario.
#34 Updated by Artur Școlnic 3 days ago
- Priority changed from Normal to High
#35 Updated by Artur Școlnic 3 days ago
Query shaped like the case in Daniel's note, trunk r16860, PostgreSQL, one session, no concurrent commits.
A dynamic NO-LOCK query read with GET-NEXT: a datetime field compared with a datetime written as a string, OR unknown, BY the primary index. 1M rows, 990k match:FOR EACH customer NO-LOCK WHERE (customer.created <= '<datetime as string>' or customer.created = ?) BY customer.customerNum
| Query | Paging off | legacy-remote page 16 |
|---|---|---|
| plain (no FORWARD-ONLY) | 116-121 s | 118-124 s |
| FORWARD-ONLY | 3.6-4.0 s | 4.9-6.2 s |
Generated SQL: where (created <= ? or created is null) order by customer_num, recid limit ? offset ?. The literal becomes a parameter, so no UDF is called per row.
- Plain query: most of the time goes to reloading every row on its own,
select ... from customer where recid = ?, ~110 µs per row locally. With a ~1.5 ms network round trip, 9M rows would spend hours on this alone (extrapolated, not measured). - FORWARD-ONLY: the cost is the OFFSET brackets. A bracket at row 900k reads all 901k rows before it: 247 ms here, with the data in cache. With millions of rows that don't fit in cache, each deep bracket reads from disk and can take far longer (not measured).
- PagedResults doesn't help yet, as in the first benchmark. Page at row 900k: OFFSET 247 ms,
PagedResults(customer_num > ? or customer_num is null) 145 ms, withoutor ... is null0.25 ms.
Alex, in the application code the slow query is opened without FORWARD-ONLY, so it runs as the plain query above. On this read path it is only navigated with GET-FIRST followed by GET-NEXT, so setting FORWARD-ONLY there is safe and was ~30x faster in this test. I think it can be set only for this read path, not where the query object is opened: the same object also serves callers that scroll (GET-PREV, GET-LAST, REPOSITION-TO-ROWID), and those would fail on a FORWARD-ONLY query.
#36 Updated by Daniel Mocsi 3 days ago
Artur Școlnic wrote:
so setting FORWARD-ONLY there is safe and was ~30x faster in this test. I think it can be set only for this read path, not where the query object is opened: the same object also serves callers that scroll (
GET-PREV,GET-LAST,REPOSITION-TO-ROWID), and those would fail on a FORWARD-ONLY query.
I believe we attempted a run where FORWARD-ONLY was set. Also, the get-prev, get-last, reposition-to-rowid scenarios seemed to be dead code.
Problem is, when placed on test environment, it showed zero performance improvement, perhaps because ProgressiveResults was already optimized to store PK-only, whereas in the past it would store the full object. I could be wrong, and perhaps for some reason the queries still ran without FORWARD-ONLY.
#37 Updated by Artur Școlnic 3 days ago
That fits your profile in #12120. FORWARD-ONLY removes the per-row reloads (select ... where recid = ?, which is what the PK-only storage costs), but it keeps the OFFSET brackets. With 1M rows in cache the reloads dominate (~30x here); with ~9M rows not in cache the brackets dominate, so FORWARD-ONLY barely shows.
To confirm it was in effect: it must be set before QUERY-OPEN, and the PostgreSQL log then shows no single-row where recid = ? SELECTs during the walk.
The fix for the brackets is reference-row paging (PagedResults with an index-usable condition, #11980) for shared-memory databases, which is the next step here.
#38 Updated by Daniel Mocsi 3 days ago
I can guarantee it was set before QUERY-OPEN, but can't check the postgresql log. I would say it's most likely the change was in effect with no improvement
#39 Updated by Daniel Mocsi 3 days ago
The past few days I asked Guido to run some EXPLAIN ( ANALYZE, BUFFERS ) statements on customer database with the actual SELECT query that is run
On that table,
OFFSET 1M LIMIT 10000 takes around 4-5s
OFFSET 8M LIMIT 10000 takes 30s+
The cache job for this table isn't run very often though.
Committing in batches of 1000 instead of once per row, brought the performance very close to what is observed in OE (2-4x improvement)
However, on some of the other larger tables, the performance is still 2-4x worse than OE.
One such example is prj_kbwnrm, which has 1.7M records, takes 9min in OE and 36 min in FWD and the FQL for it is
select prjKbwnrm from PrjKbwnrm__Impl__ as prjKbwnrm order by upper(rtrim(prjKbwnrm.bedr)) asc, upper(rtrim(prjKbwnrm.prjadm)) asc, upper(rtrim(prjKbwnrm.prj)) asc, upper(rtrim(prjKbwnrm.kosSrt)) asc, upper(rtrim(prjKbwnrm.kbwN1)) asc, upper(rtrim(prjKbwnrm.kbwN2)) asc, upper(rtrim(prjKbwnrm.kbwN3)) asc, upper(rtrim(prjKbwnrm.kbwN4)) asc, upper(rtrim(prjKbwnrm.ksr)) asc, upper(rtrim(prjKbwnrm.perType)) asc, prjKbwnrm.periode asc, prjKbwnrm.recid asc
Profiling the whole job revealed that 82% of the time is spent waiting on the results of that query. We will run some more EXPLAIN commands today to check how the OFFSET impacts this specific one.
#40 Updated by Artur Școlnic 3 days ago
Thanks, this confirms the root cause: each ProgressiveResults bracket re-reads every row before its OFFSET, so a long walk gets slower the deeper it goes (~4 µs per skipped row on your database, mostly disk reads). FORWARD-ONLY keeps these brackets, which is why it brought no gain.
PagedResultsis meant to replaceOFFSET: it asks for the next page starting after the last row read (the reference row).- Today its steps use
(k > ? or k is null). TheORstops PostgreSQL starting at the reference row in the index, so each page also re-reads from the start, and it is no faster thanOFFSET(see the benchmark above). - #11980 splits these steps into
k > ?andk is null, so each page starts at the reference row and costs only its own rows. - The walk must then actually run on
PagedResults. Today that happens only withlegacy-remoteand FORWARD-ONLY or iterating queries; shared-memory databases still useProgressiveResultsuntil the next step of this task.
Next I will check point 3: PagedResults with 11980a against trunk, on a testcase that replicates this query (wide rows, multi-field character index, a filter the index can't serve, 1M-8M rows), with legacy-remote on.
#42 Updated by Alexandru Lungu 3 days ago
Daniel, lets continue talk on #12229 as that is private and customer specific. We can feel more comfortable sharing insights on problematic code we can look at and assess #12020 viability on top of that.