You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2022/09/25 23:07:31 UTC

[GitHub] [arrow-datafusion] isidentical opened a new pull request, #3614: Optimize `regex_replace` for scalar patterns

isidentical opened a new pull request, #3614:
URL: https://github.com/apache/arrow-datafusion/pull/3614

   # Which issue does this PR close?
   
   Closes #3613.
   
   # Rationale for this change
   @Dandandan noticed `regex_replace` with a known pattern seems to be taking an extremely long amount of time during ClickBench suite in #3518. This seems to be true due to many factors, but mainly due to how generic `regex_replace` implementation is (it can handle 2⁴ combinations when it comes to scalars/arrays). Having a generic version ready is good for compatibility, but at the same time, it makes us pay the overhead for common cases (like the example in #3518, where the pattern is static).
   
   # What changes are included in this PR?
   This PR adds a scalarity (not sure if this is a real word) based specialization system where at the **runtime** the best `regex_replace` variation can be picked and executed for the given set of inputs. The system here is just the start, and if there is enough gains we might add a third case where the replacement is also known.
   
   # Are there any user-facing changes?
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   This is mainly an optimization, and there shouldn't be any user facing changes.
   
   # Benchmarks
   
   Running all benchmarks with `--release` mode (using the datafusion-cli crate with `-f` option).
   
   The initial benchmark is the Query 28 from clickhouse
   ```sql
   SELECT
       REGEXP_REPLACE("Referer", '^https?://(?:www.)?([^/]+)/.*$', '1') AS k,
       AVG(length("Referer")) AS l,
       COUNT(*) AS c,
       MIN("Referer")
   FROM hits_1
       WHERE "Referer" <> ''
       GROUP BY k
       HAVING COUNT(*) > 100000
       ORDER BY l DESC
   LIMIT 25;
   ```
   
   |                               | Master        | This Branch   | Factor         |
   |-------------------------------|---------------|---------------|----------------|
   | Cold Run                      | 2.875 seconds | 0.318 seconds | 9.04x speed-up |
   | Hot Run (6th consecutive run) | 2.252 seconds | 0.266 seconds | 8.46x speed-up |
   | Average                       | 2.408 seconds | 0.277 seconds | 8.69x speed-up |
   
   (Note: I don't have the full ClickBench data, just have a partition of it [1/100 scale] so this might not be very reflective)
   
   A second benchmark is the one where we have both the source and the replacements as arrays, which shows speed-up factor of  1.7X.
   
   ```sql
   -- Generate data
   --
   -- import secrets
   -- import random
   --
   -- rows = 1_000_000
   --
   -- data = {"user_id": [], "website": []}
   -- for _ in range(rows):
   --     data["user_id"].append(secrets.token_hex(8))
   --
   --     # Sometimes it is proper URL, and sometimes it is not.
   --     data["website"].append(
   --         random.choice(["http", "https", "unknown", ""])
   --         + random.choice([":", "://"])
   --         + random.choice(["google", "facebook"])
   --         + random.choice([".com", ".org", ""])
   --     )
   --
   -- import pandas as pd
   -- df = pd.DataFrame(data)
   -- df.to_parquet("data.parquet")
   
   CREATE EXTERNAL TABLE generated_data
   STORED AS PARQUET
   LOCATION 'data.parquet';
   
   -- Query 1
   EXPLAIN ANALYZE
   SELECT
       REGEXP_REPLACE("website", '^https?://(?:www.)?([^/]+)$', "user_id") AS encoded_website
   FROM generated_data;
   ```
   ### TODO
   - [ ] Still needs tests.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] isidentical commented on a diff in pull request #3614: Optimize `regex_replace` for scalar patterns

Posted by GitBox <gi...@apache.org>.
isidentical commented on code in PR #3614:
URL: https://github.com/apache/arrow-datafusion/pull/3614#discussion_r980582282


##########
datafusion/physical-expr/src/regex_expressions.rs:
##########
@@ -178,10 +197,125 @@ pub fn regexp_replace<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef>
     }
 }
 
+fn _regexp_replace_early_abort<T: OffsetSizeTrait>(
+    input_array: &GenericStringArray<T>,
+) -> Result<ArrayRef> {
+    // Mimicing the existing behavior of regexp_replace, if any of the scalar arguments
+    // are actuall null, then the result will be an array of the same size but with nulls.
+    Ok(new_null_array(input_array.data_type(), input_array.len()))
+}
+
+fn _regexp_replace_static_pattern<T: OffsetSizeTrait>(
+    args: &[ArrayRef],
+) -> Result<ArrayRef> {
+    // Special cased regex_replace implementation for the scenerio where
+    // both the pattern itself and the flags are scalars. This means we can
+    // skip regex caching system and basically hold a single Regex object
+    // for the replace operation.
+
+    let string_array = downcast_string_array_arg!(args[0], "string", T);
+    let pattern = fetch_string_arg!(args[1], "pattern", T, _regexp_replace_early_abort);
+    let replacement_array = downcast_string_array_arg!(args[2], "replacement", T);
+    let flags = match args.len() {
+        3 => None,
+        4 => Some(fetch_string_arg!(args[3], "flags", T, _regexp_replace_early_abort)),
+        other => {
+            return Err(DataFusionError::Internal(format!(
+                "regexp_replace was called with {} arguments. It requires at least 3 and at most 4.",
+                other
+            )))
+        }
+    };
+
+    // Embed the flag (if it exists) into the pattern
+    let (pattern, replace_all) = match flags {
+        Some("g") => (pattern.to_string(), true),
+        Some(flags) => (
+            format!("(?{}){}", flags.to_string().replace('g', ""), pattern),
+            flags.contains('g'),
+        ),
+        None => (pattern.to_string(), false),
+    };
+
+    let re = Regex::new(&pattern)
+        .map_err(|err| DataFusionError::Execution(err.to_string()))?;
+
+    let result = string_array
+        .iter()
+        .zip(replacement_array.iter())

Review Comment:
   |                                                                    | generic replacement (this PR) | specialized replacement (isidentical/arrow-datafusion#2) | Overall Factor (compared to master)       | Relative Factor (compared to existing impl) |
   |--------------------------------------------------------------------|---------------------|-------------------------|-------------------------------------------|---------------------------------------------|
   | Query 1                                                            | 0.269 seconds       | 0.104 seconds           | 23.1x speed-up                            | 2.5x speed-up                               |
   | Query 2                                                            | 2.803 seconds       | 4.823 seconds           | None (only slight noise), nothing changed | 1.7x slowdown                               |
   | Query 2 ( **same query but this time the third arg is a scalar** ) | 2.753 seconds       | 0.138 seconds           | 34.9x speed-up                            | 19.9x speed-up                              |
   
   Results seems really interesting for the Query 1, and as expected no change for Query 2. The third row is when we change Query 2 to use a scalar (instead of a column), and that an even more amazing speed-up. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] Dandandan commented on a diff in pull request #3614: Optimize `regex_replace` for scalar patterns

Posted by GitBox <gi...@apache.org>.
Dandandan commented on code in PR #3614:
URL: https://github.com/apache/arrow-datafusion/pull/3614#discussion_r980254141


##########
datafusion/physical-expr/src/regex_expressions.rs:
##########
@@ -178,10 +197,125 @@ pub fn regexp_replace<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef>
     }
 }
 
+fn _regexp_replace_early_abort<T: OffsetSizeTrait>(
+    input_array: &GenericStringArray<T>,
+) -> Result<ArrayRef> {
+    // Mimicing the existing behavior of regexp_replace, if any of the scalar arguments
+    // are actuall null, then the result will be an array of the same size but with nulls.
+    Ok(new_null_array(input_array.data_type(), input_array.len()))
+}
+
+fn _regexp_replace_static_pattern<T: OffsetSizeTrait>(
+    args: &[ArrayRef],
+) -> Result<ArrayRef> {
+    // Special cased regex_replace implementation for the scenerio where
+    // both the pattern itself and the flags are scalars. This means we can
+    // skip regex caching system and basically hold a single Regex object
+    // for the replace operation.
+
+    let string_array = downcast_string_array_arg!(args[0], "string", T);
+    let pattern = fetch_string_arg!(args[1], "pattern", T, _regexp_replace_early_abort);
+    let replacement_array = downcast_string_array_arg!(args[2], "replacement", T);
+    let flags = match args.len() {
+        3 => None,
+        4 => Some(fetch_string_arg!(args[3], "flags", T, _regexp_replace_early_abort)),
+        other => {
+            return Err(DataFusionError::Internal(format!(
+                "regexp_replace was called with {} arguments. It requires at least 3 and at most 4.",
+                other
+            )))
+        }
+    };
+
+    // Embed the flag (if it exists) into the pattern
+    let (pattern, replace_all) = match flags {
+        Some("g") => (pattern.to_string(), true),
+        Some(flags) => (
+            format!("(?{}){}", flags.to_string().replace('g', ""), pattern),
+            flags.contains('g'),
+        ),
+        None => (pattern.to_string(), false),
+    };
+
+    let re = Regex::new(&pattern)
+        .map_err(|err| DataFusionError::Execution(err.to_string()))?;
+
+    let result = string_array
+        .iter()
+        .zip(replacement_array.iter())

Review Comment:
   I guess the case with both a scalar replacement + scalar pattern (as in the example query) might be the most common - so maybe best to implement this case in this PR?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] Dandandan merged pull request #3614: Optimize `regex_replace` for scalar patterns

Posted by GitBox <gi...@apache.org>.
Dandandan merged PR #3614:
URL: https://github.com/apache/arrow-datafusion/pull/3614


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] codecov-commenter commented on pull request #3614: Optimize `regex_replace` for scalar patterns

Posted by GitBox <gi...@apache.org>.
codecov-commenter commented on PR #3614:
URL: https://github.com/apache/arrow-datafusion/pull/3614#issuecomment-1257315729

   # [Codecov](https://codecov.io/gh/apache/arrow-datafusion/pull/3614?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) Report
   > Merging [#3614](https://codecov.io/gh/apache/arrow-datafusion/pull/3614?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (fe85ff8) into [master](https://codecov.io/gh/apache/arrow-datafusion/commit/ebb28f54049813f1990a44ca75a8867175633180?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) (ebb28f5) will **decrease** coverage by `0.09%`.
   > The diff coverage is `67.21%`.
   
   ```diff
   @@            Coverage Diff             @@
   ##           master    #3614      +/-   ##
   ==========================================
   - Coverage   86.07%   85.97%   -0.10%     
   ==========================================
     Files         300      300              
     Lines       56314    56361      +47     
   ==========================================
   - Hits        48473    48459      -14     
   - Misses       7841     7902      +61     
   ```
   
   
   | [Impacted Files](https://codecov.io/gh/apache/arrow-datafusion/pull/3614?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation) | Coverage Δ | |
   |---|---|---|
   | [datafusion/physical-expr/src/functions.rs](https://codecov.io/gh/apache/arrow-datafusion/pull/3614/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-ZGF0YWZ1c2lvbi9waHlzaWNhbC1leHByL3NyYy9mdW5jdGlvbnMucnM=) | `92.66% <50.00%> (-0.10%)` | :arrow_down: |
   | [datafusion/physical-expr/src/regex\_expressions.rs](https://codecov.io/gh/apache/arrow-datafusion/pull/3614/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-ZGF0YWZ1c2lvbi9waHlzaWNhbC1leHByL3NyYy9yZWdleF9leHByZXNzaW9ucy5ycw==) | `50.31% <68.42%> (-32.72%)` | :arrow_down: |
   | [datafusion/common/src/scalar.rs](https://codecov.io/gh/apache/arrow-datafusion/pull/3614/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-ZGF0YWZ1c2lvbi9jb21tb24vc3JjL3NjYWxhci5ycw==) | `85.18% <0.00%> (-0.07%)` | :arrow_down: |
   | [datafusion/expr/src/logical\_plan/plan.rs](https://codecov.io/gh/apache/arrow-datafusion/pull/3614/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation#diff-ZGF0YWZ1c2lvbi9leHByL3NyYy9sb2dpY2FsX3BsYW4vcGxhbi5ycw==) | `77.10% <0.00%> (ø)` | |
   
   :mega: We’re building smart automated test selection to slash your CI/CD build times. [Learn more](https://about.codecov.io/iterative-testing/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=The+Apache+Software+Foundation)
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] Dandandan commented on pull request #3614: Optimize `regex_replace` for scalar patterns

Posted by GitBox <gi...@apache.org>.
Dandandan commented on PR #3614:
URL: https://github.com/apache/arrow-datafusion/pull/3614#issuecomment-1259044888

   Thank you @isidentical !


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] isidentical commented on a diff in pull request #3614: Optimize `regex_replace` for scalar patterns

Posted by GitBox <gi...@apache.org>.
isidentical commented on code in PR #3614:
URL: https://github.com/apache/arrow-datafusion/pull/3614#discussion_r980571403


##########
datafusion/physical-expr/src/regex_expressions.rs:
##########
@@ -178,10 +197,125 @@ pub fn regexp_replace<T: OffsetSizeTrait>(args: &[ArrayRef]) -> Result<ArrayRef>
     }
 }
 
+fn _regexp_replace_early_abort<T: OffsetSizeTrait>(
+    input_array: &GenericStringArray<T>,
+) -> Result<ArrayRef> {
+    // Mimicing the existing behavior of regexp_replace, if any of the scalar arguments
+    // are actuall null, then the result will be an array of the same size but with nulls.
+    Ok(new_null_array(input_array.data_type(), input_array.len()))
+}
+
+fn _regexp_replace_static_pattern<T: OffsetSizeTrait>(
+    args: &[ArrayRef],
+) -> Result<ArrayRef> {
+    // Special cased regex_replace implementation for the scenerio where
+    // both the pattern itself and the flags are scalars. This means we can
+    // skip regex caching system and basically hold a single Regex object
+    // for the replace operation.
+
+    let string_array = downcast_string_array_arg!(args[0], "string", T);
+    let pattern = fetch_string_arg!(args[1], "pattern", T, _regexp_replace_early_abort);
+    let replacement_array = downcast_string_array_arg!(args[2], "replacement", T);
+    let flags = match args.len() {
+        3 => None,
+        4 => Some(fetch_string_arg!(args[3], "flags", T, _regexp_replace_early_abort)),
+        other => {
+            return Err(DataFusionError::Internal(format!(
+                "regexp_replace was called with {} arguments. It requires at least 3 and at most 4.",
+                other
+            )))
+        }
+    };
+
+    // Embed the flag (if it exists) into the pattern
+    let (pattern, replace_all) = match flags {
+        Some("g") => (pattern.to_string(), true),
+        Some(flags) => (
+            format!("(?{}){}", flags.to_string().replace('g', ""), pattern),
+            flags.contains('g'),
+        ),
+        None => (pattern.to_string(), false),
+    };
+
+    let re = Regex::new(&pattern)
+        .map_err(|err| DataFusionError::Execution(err.to_string()))?;
+
+    let result = string_array
+        .iter()
+        .zip(replacement_array.iter())

Review Comment:
   I was thinking about it but then decided the overhead could be neglected for replacements in the initial revision (since the implementation here can specialize on both that case already, and the case with non-scaalar replacements). Now that you are also mentioning it, I guess it would be worth to benchmark this revision against the replacement one.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [arrow-datafusion] ursabot commented on pull request #3614: Optimize `regex_replace` for scalar patterns

Posted by GitBox <gi...@apache.org>.
ursabot commented on PR #3614:
URL: https://github.com/apache/arrow-datafusion/pull/3614#issuecomment-1259054242

   Benchmark runs are scheduled for baseline = ea3dbb6fb887b0f58ff113c9b46f743d73c41a67 and contender = 15c19c3140f4a03b169416ac88074065da5946e7. 15c19c3140f4a03b169416ac88074065da5946e7 is a master commit associated with this PR. Results will be available as each benchmark for each run completes.
   Conbench compare runs links:
   [Skipped :warning: Benchmarking of arrow-datafusion-commits is not supported on ec2-t3-xlarge-us-east-2] [ec2-t3-xlarge-us-east-2](https://conbench.ursa.dev/compare/runs/37d00068e1964af28ede3c872a05897c...8632b580626d4559ba43e6fae396b9e5/)
   [Skipped :warning: Benchmarking of arrow-datafusion-commits is not supported on test-mac-arm] [test-mac-arm](https://conbench.ursa.dev/compare/runs/f6c9f41825884684918a6c386daeb0f2...73d7282280474c93966c1d088522fa2d/)
   [Skipped :warning: Benchmarking of arrow-datafusion-commits is not supported on ursa-i9-9960x] [ursa-i9-9960x](https://conbench.ursa.dev/compare/runs/5d617ce7792549f89eb49c4fb165dc62...0543837491c440b9997ffb9e4e4e22f0/)
   [Skipped :warning: Benchmarking of arrow-datafusion-commits is not supported on ursa-thinkcentre-m75q] [ursa-thinkcentre-m75q](https://conbench.ursa.dev/compare/runs/19a1b9cbf1fc473389e1df67748326f7...aad8fb2c66404ee9be7f493ec3f03ba9/)
   Buildkite builds:
   Supported benchmarks:
   ec2-t3-xlarge-us-east-2: Supported benchmark langs: Python, R. Runs only benchmarks with cloud = True
   test-mac-arm: Supported benchmark langs: C++, Python, R
   ursa-i9-9960x: Supported benchmark langs: Python, R, JavaScript
   ursa-thinkcentre-m75q: Supported benchmark langs: C++, Java
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org