Skip to content

stream_processor: fix operator precedence for logical operations#9388

Open
unitmatrix wants to merge 1 commit intofluent:masterfrom
unitmatrix:fix-sql-conditions
Open

stream_processor: fix operator precedence for logical operations#9388
unitmatrix wants to merge 1 commit intofluent:masterfrom
unitmatrix:fix-sql-conditions

Conversation

@unitmatrix
Copy link

@unitmatrix unitmatrix commented Sep 14, 2024

Fixes #3763

Summary

This pull request addresses the issue where the precedence of logical operators (AND, OR, NOT) was not defined in the grammar for the stream processor.

Changes Made

  • Added precedence rules for NOT, AND, and OR operators to the Bison grammar file.
    • NOT now has the highest precedence.
    • AND has middle precedence.
    • OR has the lowest precedence.

Issue Addressed

Fixes GitHub issue: stream_processor: precedence of AND, OR, and NOT not defined in grammar.

Impact

This change ensures that logical operations in conditions are parsed with the correct precedence, aligning with expected logical operation rules.

Testing

Please verify that the logical operations in conditions are handled correctly according to the new precedence rules.

Feel free to reach out if there are any questions or further adjustments needed.

Summary by CodeRabbit

  • Bug Fixes

    • Corrected boolean operator precedence in queries: NOT now binds tighter than AND, which binds tighter than OR, ensuring accurate evaluation of complex WHERE clauses.
  • Tests

    • Added tests covering AND/OR/NOT precedence combinations to validate parsing and prevent regressions.
  • Chores

    • Updated parser/public interface and symbol naming — may affect integrations that call the parser directly.

@koleini
Copy link
Contributor

koleini commented Sep 17, 2024

Thanks @unitmatrix, it would be great if the syntax (https://github.com/fluent/fluent-bit/tree/master/src/stream_processor#sql-statement-syntax) can be updated based on your changes as well.

@unitmatrix
Copy link
Author

Hi @koleini,

Thank you for your feedback. To ensure that I address your request accurately, I revisited my changes and believe they do not impact the existing SQL statement syntax as outlined in the documentation. Could you please specify which part of the syntax might be affected, or if there are specific updates you have in mind? This will help me make the necessary adjustments to the documentation more effectively.

Looking forward to your guidance.
Best regards.

@unitmatrix
Copy link
Author

Hi team,

I hope everyone is doing well. I wanted to follow up on this pull request submitted on Sep 14. I've made the necessary updates based on the pipeline checks and have responded to all the questions so far. Could someone please provide an update on the status of this PR? I'm looking forward to any further feedback or actions needed to move this forward.

Thank you for your time!

@github-actions
Copy link
Contributor

This PR is stale because it has been open 45 days with no activity. Remove stale label or comment or this will be closed in 10 days.

@github-actions github-actions bot added the Stale label Feb 13, 2025
@github-actions github-actions bot removed the Stale label Mar 23, 2025
@edsiper
Copy link
Member

edsiper commented Apr 23, 2025

@koleini @unitmatrix is this ready to go ?

@edsiper edsiper added this to the Fluent Bit Next milestone Apr 23, 2025
@unitmatrix
Copy link
Author

This PR is ready to go, @edsiper.

@koleini
Copy link
Contributor

koleini commented Aug 15, 2025

Hi @unitmatrix, I reviewed the BNF syntax and looks like it requires further cleaning up, which will take care of it.

I am just wondering if your test functions would cover all the combinations and ensures the precedence is implemented correctly: NOT > AND > OR. Would you please verify?

@coderabbitai
Copy link

coderabbitai bot commented Aug 16, 2025

Walkthrough

Adds operator precedence rules for boolean expressions (NOT > AND > OR), updates Bison name-prefix syntax and parser parse-params, adds a destructor for IDENTIFIER tokens, and introduces three tests and callbacks validating boolean precedence in WHERE clauses.

Changes

Cohort / File(s) Summary
Parser grammar updates
src/stream_processor/parser/sql.y
Change Bison name-prefix syntax to %name-prefix "flb_sp_"; add precedence/associativity directives (%right NOT, %left AND, %left OR); add +%parse-param { const char *query };; add %destructor { flb_free ($$); } IDENTIFIER; annotate NOT condition with %prec NOT.
Test callbacks for precedence
tests/internal/include/sp_cb_functions.h
Add three static callbacks: cb_select_and_or_precedence, cb_select_not_or_precedence, cb_select_not_and_precedence that count rows and assert expected results.
SELECT keys tests for precedence
tests/internal/include/sp_select_keys.h
Append three tests (ids 18–20) exercising AND/OR/NOT precedence with the new callbacks and queries targeting WHERE clauses combining NOT/AND/OR.

Sequence Diagram(s)

sequenceDiagram
  participant Test as Test Case
  participant Parser as Lexer/Bison Parser
  participant AST as AST
  participant Eval as Evaluator
  participant CB as Test Callback

  Test->>Parser: Submit SQL query with WHERE using NOT/AND/OR
  Parser->>AST: Parse and build AST using precedence (NOT > AND > OR)
  AST->>Eval: Evaluate expression per row
  Eval-->>Test: Return result set
  Test->>CB: Invoke callback with results
  CB-->>Test: Perform assertions
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Define precedence of AND, OR, NOT in grammar and ensure correct parsing semantics (#3763)

Assessment against linked issues: Out-of-scope changes

Code Change Explanation
Change Bison name-prefix directive syntax (src/stream_processor/parser/sql.y) Affects generated symbol naming and public symbol names; not required to address operator precedence.
Added %parse-param { const char *query } to parser signature (src/stream_processor/parser/sql.y) Expands parser public API with an extra parameter unrelated to precedence fix or the linked issue.

I twitch my whiskers, parse the breeze,
NOT hops first, then AND with ease;
OR drifts last along the way,
tests count rows and cheer hooray—
carrots crunch, the parser sings 🥕🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 53795fc and a722215.

📒 Files selected for processing (3)
  • src/stream_processor/parser/sql.y (3 hunks)
  • tests/internal/include/sp_cb_functions.h (1 hunks)
  • tests/internal/include/sp_select_keys.h (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • tests/internal/include/sp_cb_functions.h
  • tests/internal/include/sp_select_keys.h
  • src/stream_processor/parser/sql.y
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
tests/internal/include/sp_select_keys.h (1)

130-148: Consider adding a couple more precedence/associativity cases.

Optional but useful to harden coverage:

  • true OR false AND false should be parsed as true OR (false AND false) -> true (11 rows).
  • true AND true OR false should be (true AND true) OR false -> true (11 rows).
  • NOT false OR false -> true OR false -> true (11 rows).
  • true AND NOT false -> true AND true -> true (11 rows).

I can add these to the suite if you want.

src/stream_processor/parser/sql.y (2)

1-1: Use modern Bison directive for symbol prefix (cleaner and future-proof).

The inline comment already hints at it. Prefer %define api.prefix {flb_sp_} over %name-prefix "flb_sp_".

Apply this diff:

-%name-prefix "flb_sp_"  // replace with %define api.prefix {flb_sp_}
+%define api.prefix {flb_sp_}

101-104: Optional: make NOT’s precedence explicit on the rule with %prec.

Bison assigns a rule’s precedence from its rightmost terminal, so NOT condition already picks up NOT’s precedence. Adding %prec NOT on the rule makes intent explicit and guards against future edits:

Outside this hunk, update the rule as:

condition: NOT condition %prec NOT
{
  $$ = flb_sp_cmd_operation(cmd, $2, NULL, FLB_EXP_NOT);
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between c51a9e4 and ca73d7b.

📒 Files selected for processing (3)
  • src/stream_processor/parser/sql.y (2 hunks)
  • tests/internal/include/sp_cb_functions.h (1 hunks)
  • tests/internal/include/sp_select_keys.h (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/internal/include/sp_select_keys.h (1)
tests/internal/include/sp_cb_functions.h (1)
  • cb_select_and_or_precedence (209-217)
🔇 Additional comments (4)
tests/internal/include/sp_cb_functions.h (3)

209-218: New AND/OR precedence callback looks correct (expects 11 rows).

Expression false AND true OR true parses as (false AND true) OR true -> true; expecting all 11 rows is correct.


219-227: New NOT/OR precedence callback looks correct (expects 11 rows).

Expression NOT true OR true parses as (NOT true) OR true -> false OR true -> true; expecting all 11 rows is correct.


229-237: New NOT/AND precedence callback looks correct (expects 0 rows).

Expression NOT true AND false parses as (NOT true) AND false -> false AND false -> false; expecting 0 rows is correct.

src/stream_processor/parser/sql.y (1)

101-104: Manual Bison Conflict Verification Required

The precedence and associativity declarations for NOT > AND > OR are correct and align with standard logical rules. However, since Bison isn’t available in this environment, please run the following in your local setup to ensure there are no lingering shift/reduce conflicts:

  • Generate a Bison report and check for conflicts:
    bison --report=states,solved,lookahead --report-file=sql.output src/stream_processor/parser/sql.y
    rg -n "conflicts:" sql.output || echo "No conflicts found"

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
tests/internal/include/sp_select_keys.h (1)

130-148: Add a couple more edge-case tests to harden coverage

Two quick additions would increase confidence in associativity and parenthesized overrides:

  • Chained OR/AND associativity:
    • true OR true AND false → expect all rows (AND binds before OR).
    • true AND true AND false → expect 0 rows (left associativity).
  • Parentheses override:
    • NOT (true OR true) → expect 0 rows (ensures NOT applies after grouped OR).

I can draft the test entries if helpful.

src/stream_processor/parser/sql.y (2)

101-104: Precedence directives LGTM; consider switching to C-style comments for consistency

The precedence levels are correct (OR lowest, AND middle, NOT highest). For consistency with the rest of this grammar file, prefer C-style comments.

-/* Define operator precedence and associativity for logical operations in conditions */
-%left OR   // Lowest precedence for OR
-%left AND  // Middle precedence for AND
-%right NOT // Highest precedence for NOT
+/* Define operator precedence and associativity for logical operations in conditions */
+%left OR   /* Lowest precedence for OR */
+%left AND  /* Middle precedence for AND */
+%right NOT /* Highest precedence for NOT */

1-1: Prefer modern Bison directive: %define api.prefix {flb_sp_}

%name-prefix is deprecated. Switching to the modern form avoids future warnings and matches current Bison conventions.

-%name-prefix "flb_sp_"  // replace with %define api.prefix {flb_sp_}
+%define api.prefix {flb_sp_}

If your CI uses an older Bison, confirm it supports api.prefix (it’s available in Bison 2.6+).

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between ca73d7b and 53795fc.

📒 Files selected for processing (3)
  • src/stream_processor/parser/sql.y (2 hunks)
  • tests/internal/include/sp_cb_functions.h (1 hunks)
  • tests/internal/include/sp_select_keys.h (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/internal/include/sp_cb_functions.h
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/internal/include/sp_select_keys.h (1)
tests/internal/include/sp_cb_functions.h (3)
  • cb_select_and_or_precedence (209-217)
  • cb_select_not_or_precedence (219-227)
  • cb_select_not_and_precedence (229-237)
🔇 Additional comments (2)
tests/internal/include/sp_select_keys.h (1)

130-148: New precedence tests are correct and consistent with callbacks

  • The three queries exercise the intended precedence (NOT > AND > OR).
  • The callbacks now match the actual implementations in sp_cb_functions.h; this resolves the earlier “cb_select_not_precedence” mismatch.

Looks good.

src/stream_processor/parser/sql.y (1)

1-1: flb_sp_parse call sites correctly updated

No missing invocations found after adding the query parameter:

  • src/stream_processor/parser/flb_sp_parser.c:396 – ret = flb_sp_parse(cmd, sql, scanner);
  • No occurrences of flb_sp_yyparse( elsewhere

Lexer prototype remains unchanged (extern int yylex();), consistent with reentrant scanner usage.

@unitmatrix
Copy link
Author

Hi @unitmatrix, I reviewed the BNF syntax and looks like it requires further cleaning up, which will take care of it.

I am just wondering if your test functions would cover all the combinations and ensures the precedence is implemented correctly: NOT > AND > OR. Would you please verify?

Hi @koleini. Added 'NOT' > 'AND' test for completeness. Thank you.

Signed-off-by: Aleksandr Cupacenko <apaxuc@gmail.com>

revert definition removal

Signed-off-by: Aleksandr Cupacenko <apaxuc@gmail.com>

add operator precedence unit tests

correct precedencer order

add not_and precedent check

correct function references

ai suggestion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

stream_processor: precedence of AND, OR, and NOT not defined in grammar

3 participants