Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify toQueryString to prevent SQLite expression tree from exceeding depth of 1000 #2565

Open
wants to merge 14 commits into
base: master
Choose a base branch
from

Conversation

LZRS
Copy link
Collaborator

@LZRS LZRS commented Jun 8, 2024

IMPORTANT: All PRs must be linked to an issue (except for extremely trivial and straightforward changes).

Fixes #2561

Description
Recursively bifurcates the conditional params expressions to prevent occurences of SQLite expression tree exceeding depth of 1000, as suggested in this comment

Alternative(s) considered
Chunking large expression list to limit 50 within parantheses to avoid crashing with Expression tree is too large (maximum depth 1000), as described here

Type
Enhancement Feature

Screenshots (if applicable)

Checklist

  • I have read and acknowledged the Code of conduct.
  • I have read the Contributing page.
  • I have signed the Google Individual CLA, or I am covered by my company's Corporate CLA.
  • I have discussed my proposed solution with code owners in the linked issue(s) and we have agreed upon the general approach.
  • I have run ./gradlew spotlessApply and ./gradlew spotlessCheck to check my code follows the style guide of this project.
  • I have run ./gradlew check and ./gradlew connectedCheck to test my changes locally.
  • I have built and run the demo app(s) to verify my change fixes the issue and/or does not break the demo app(s).

"(${it.condition})"
} else {
it.condition
this.chunked(50) { conditionParams ->
Copy link
Collaborator

@pld pld Jun 14, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@MJ1998 do you have thoughts on what the chunk size should be?

@LZRS LZRS marked this pull request as ready for review June 21, 2024 17:52
* This is to prevent SQLite expression tree exceeding max depth of 1000 See
* https://www.sqlite.org/limits.html for Maximum Depth Of An Expression Tree
*/
const val CONDITION_PARAMS_CHUNK_SIZE = 50
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

another question on this value, don't we want this to be as high as possible? I'd think fewer chunks are easier to process, and fewer checks definitely means fewer iterations. Why not set this to the max of 1000 as a default?

Copy link
Collaborator Author

@LZRS LZRS Jun 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, you're right, the chunk size could be higher. Most of the filters for FhirEngine#search are implemented in subqueries, it seems subqueries add to the depth expression tree generated. Will try to figure out a higher number that could be suitable...

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be hard to find a number that might be suitable for most applications because of joins and subqueries that depend on the search. I'm thinking of setting the size to a lower number and maybe allow it to be configurable

@jingtang10
Copy link
Collaborator

jingtang10 commented Jul 22, 2024

judging purely by the error message, my hypothesis is that the expression tree depth is O(n) for nested OR operators because the expression tree is constructed naively by parsing the OR operators sequentially. For example, for this expression

a OR b OR c OR d OR e OR f OR g OR h

if the expression tree is constructed naively you'd get:

  o
 / \
a   o
   / \
  b   o
     / \
    c   o
       / \
      d   o
         / \
        e   o
           / \
          f   o
             / \
            g   h

where each o stands for an OR operator. This has depth 8.

But what you really want is actually this:

        o
      /   \
    o       o
   / \     / \
  o   o   o   o
 / \ / \ / \ / \
 a b c d e f g h

where the tree is more "balanced" and this has depth 4. In other words, this is O(log(n)).

If my hypothesis of what causes the problem is correct above, instead of trying to break the OR statements into chunks (and having to come up with a value), all you actually have to do is keep the tree balanced by splitting the top level OR statment at the middle of the list of params.

Does this make sense?

@LZRS
Copy link
Collaborator Author

LZRS commented Jul 23, 2024

judging purely by the error message, my hypothesis is that the expression tree depth is O(n) for nested OR operators because the expression tree is constructed naively by parsing the OR operators sequentially. For example, for this expression

a OR b OR c OR d OR e OR f OR g OR h

if the expression tree is constructed naively you'd get:

  o
 / \
a   o
   / \
  b   o
     / \
    c   o
       / \
      d   o
         / \
        e   o
           / \
          f   o
             / \
            g   h

where each o stands for an OR operator. This has depth 8.

But what you really want is actually this:

        o
      /   \
    o       o
   / \     / \
  o   o   o   o
 / \ / \ / \ / \
 a b c d e f g h

where the tree is more "balanced" and this has depth 4. In other words, this is O(log(n)).

If my hypothesis of what causes the problem is correct above, instead of trying to break the OR statements into chunks (and having to come up with a value), all you actually have to do is keep the tree balanced by splitting the top level OR statment at the middle of the list of params.

Does this make sense?

Yeah, it makes sense.

@jingtang10
Copy link
Collaborator

there's no guarantee what i said is true @LZRS - i've done no testing or verification and depending on sqlite's implementation what i said could be complete garbage... so pls test and see if this is true :) (for example you could try to see if you'll hit the depth limit a bit later to bifurcate the tree instead of chunking the parameters)

@LZRS
Copy link
Collaborator Author

LZRS commented Jul 23, 2024

Alright, no problem. I'll test it out and get back

@LZRS LZRS requested a review from a team as a code owner August 22, 2024 00:57
@LZRS
Copy link
Collaborator Author

LZRS commented Aug 22, 2024

there's no guarantee what i said is true @LZRS - i've done no testing or verification and depending on sqlite's implementation what i said could be complete garbage... so pls test and see if this is true :) (for example you could try to see if you'll hit the depth limit a bit later to bifurcate the tree instead of chunking the parameters)

@jingtang10 I tested this out for 1000, 2000 and upto 5000 parameters, and it worked perfectly. I also went ahead a drafted an implementation in the PR

@LZRS LZRS changed the title Modify toQueryString to chunk large list of ConditionParam Modify toQueryString to prevent SQLite expression tree from exceeding depth of 1000 Aug 22, 2024
}
private fun List<ConditionParam<*>>.toQueryString(operation: Operation): String {
if (this.size <= 1) {
return map {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why use map if the size is <= 1 anyway? i think you can just do the lamba inside the map function directly since you know there's only one (or zero) item.

val left = this.subList(0, mid).toQueryString(operation)
val right = this.subList(mid, this.size).toQueryString(operation)

return listOf(left, right)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you just join left and right with the separator without going through all this? in line 89 you have guarantee that the list has 2 or more items. that means neither left nor right can have size 0.

@@ -2752,6 +2754,43 @@ class SearchTest {
.inOrder()
}

@Test
fun `search CarePlan filter with large list of patient reference`() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think you do want to also test base cases... for example an empty list, and a list with 1, 2, (maybe add a 3 just to check when the list is not an even number and power of 2), 4 and 8 items.

by that point we can be confident the algorithm works as intended.

we can have a huge one like this - but it's actually not as useful in my view.

Copy link
Collaborator Author

@LZRS LZRS Sep 11, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The base case for 1 is majorly covered in other test cases in the class, I guess I could add for the other cases

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well - I know that the base case for 1 is covered via other test cases. BUT it's much better to write unit tests for base cases than complex cases.

I would say that tests cases for 0, 1, 2, 3, 4 together is much better than a single test case for 10.

This is because you really want to isolate any cases and make sure tests are easy to debug, easy to fix. If the test case for 10 starts to fail, you'll spend a long time trying to debug. But if the test case fails for either of 1, 2, 3, or 4, you can almost immediately pin down the cause for failure.

Copy link
Collaborator

@aditya-07 aditya-07 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add a DatabaseImplTest with

@@ -2752,6 +2754,43 @@ class SearchTest {
.inOrder()
}

@Test
fun `search CarePlan filter with large list of patient reference`() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should add this test in DatabaseImplTest to make sure that it always compiles and runs on the actual database.

@@ -2752,6 +2754,43 @@ class SearchTest {
.inOrder()
}

@Test
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

would it be possible to test the depth after the tree balancing? for example, before the change, the depth was 8. but now, after the change, the depth is 4.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not really sure if it's easily possible, but checking it out...

ndegwamartin added a commit to opensrp/android-fhir that referenced this pull request Sep 10, 2024
FORK
         - With unmerged PR #9
            - WUP  #13

SDK
            - WUP google#2178
            - WUP google#2650
            - WUP google#2663
PERF
- WUP google#2669
- WUP google#2565
- WUP google#2561
- WUP google#2535
Comment on lines +92 to +96
if (it.params.size > 1) {
"(${it.condition})"
} else {
it.condition
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you make this a function in the class ConditionParam actually? will look this code look better.

it.condition
}
private fun List<ConditionParam<*>>.toQueryString(operation: Operation): String {
if (this.size <= 1) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i wonder if you can make this a bit more explicit - i think we should never have the 0 case? and for the 1 case you can make the code look tidier.

@@ -2752,6 +2754,43 @@ class SearchTest {
.inOrder()
}

@Test
fun `search CarePlan filter with large list of patient reference`() {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well - I know that the base case for 1 is covered via other test cases. BUT it's much better to write unit tests for base cases than complex cases.

I would say that tests cases for 0, 1, 2, 3, 4 together is much better than a single test case for 10.

This is because you really want to isolate any cases and make sure tests are easy to debug, easy to fix. If the test case for 10 starts to fail, you'll spend a long time trying to debug. But if the test case fails for either of 1, 2, 3, or 4, you can almost immediately pin down the cause for failure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: PR under Review
Development

Successfully merging this pull request may close these issues.

SQLite crashes with 'Expression tree is too large (maximum depth 1000)'
5 participants