github-actions[bot] commented on code in PR #41886:
URL: https://github.com/apache/beam/pull/41886#discussion_r4775730852
##########
sdks/python/apache_beam/ml/rag/enrichment/bigquery_vector_search.py:
##########
@@ -218,26 +301,28 @@ def format_query(self, items: list[EmbeddableItem]) ->
str:
));
""" if self.metadata_restriction_template else ""
- # Group items by their metadata conditions
+ # Group items by their metadata conditions. Each item is identified in the
+ # query by its position in ``items`` so that results can be mapped back
+ # to the originating item, even when several items share the same id.
condition_groups = defaultdict(list)
if self.metadata_restriction_template:
- for item in items:
+ for idx, item in enumerate(items):
condition = self._format_restrict(item)
- condition_groups[condition].append(item)
+ condition_groups[condition].append((idx, item))
else:
# No metadata filtering - all items in one group
- condition_groups[""] = items
+ condition_groups[""] = list(enumerate(items))
# Generate VECTOR_SEARCH subqueries for each condition group
vector_searches = []
for condition, group_items in condition_groups.items():
# Create embeddings subquery for this group
embedding_unions = []
- for item in group_items:
+ for idx, item in group_items:
if not item.dense_embedding:
raise ValueError(f"Item {item.id} missing embedding")
embedding_str = (
- f"SELECT '{item.id}' as id, "
+ f"SELECT {idx} as idx, "
f"{[float(x) for x in item.dense_embedding]} "
Review Comment:
**🟢 Low**: While `dense_embedding` is expected to be a list of floats,
`float(x)` allows `nan` and `inf` (which render as `[nan, inf]` in Python and
fail or behave unexpectedly in BigQuery SQL). Since `options` already validates
against non-finite floats and `_render_restriction_template` checks
`math.isfinite`, consider also validating `math.isfinite(float(x))` here or
rejecting non-finite embedding values.
##########
sdks/python/apache_beam/ml/rag/enrichment/bigquery_vector_search.py:
##########
@@ -32,6 +35,81 @@
_LOGGER = logging.getLogger(__name__)
+_NUMERIC_LITERAL_RE = re.compile(r'[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?')
+_STRING_ESCAPES = {
+ '\\': '\\\\', "'": "\\'", '"': '\\"', '\n': '\\n', '\r': '\\r'
+}
+
+
+def _escape_string_literal(value: str) -> str:
+ """Returns value encoded as the contents of a quoted BigQuery string."""
+ return re.sub(
+ r'[\\\'"\x00-\x1f\x7f]',
+ lambda m: _STRING_ESCAPES.get(m.group(), f'\\x{ord(m.group()):02x}'),
+ value)
+
+
+def _quote_after(text: str, quote: Optional[str]) -> Optional[str]:
+ """Returns the open quote (', " or `) after text, starting from quote.
+
+ Raises ValueError for comment markers outside quotes, or a backslash at the
+ end of text inside quotes.
+ """
+ i = 0
+ while i < len(text):
+ c = text[i]
+ if quote:
+ if c == '\\':
+ if i + 1 == len(text):
+ raise ValueError('A placeholder cannot follow a backslash.')
+ i += 1
+ elif c == quote:
+ quote = None
+ elif c in '\'"`':
+ quote = c
+ elif c == '#' or text.startswith(('--', '/*'), i):
+ raise ValueError(
+ 'Comments are not supported in metadata_restriction_template.')
+ i += 1
+ return quote
+
+
+def _render_restriction_template(
+ template: str, metadata: dict[str, Any]) -> str:
+ """Formats template like str.format, rendering values as SQL literals.
+
+ Values inside '...' or "..." are escaped as string contents. Values outside
+ quotes must render as a number or boolean; negative numbers are wrapped in
+ parentheses. Values must be str, int, float (finite) or bool. Anything else
+ raises ValueError.
+ """
+ formatter = string.Formatter()
+ if "'''" in template or '"""' in template:
Review Comment:
**🟡 Medium**: Two subtle edge cases with string literal handling in
`_render_restriction_template`:
1. **Escaped braces forming triple quotes:** Checking `if "'''" in template
or '"""' in template:` on the raw `template` before `formatter.parse(template)`
can be bypassed if the template contains escaped braces (e.g.,
`"'{{''{v}'''"`), because `formatter.parse` unescapes `{{` to `{` in `literal`,
producing `"'{''"`, or if `"''"` appears before an empty/escaped sequence.
Checking `literal` inside the loop (or prohibiting `r'...'`/`r"..."` raw string
prefixes where `_escape_string_literal`'s `\'` does not escape the quote in
GoogleSQL if the value ends with `\`) is more robust.
2. **GoogleSQL raw strings (`r'...'` / `r"..."`):** If a template uses a raw
string literal around a placeholder (e.g., `r'{v}'`), `_escape_string_literal`
escapes `\` as `\\` and `'` as `\'`. In GoogleSQL raw strings, `\\'` is an
escaped backslash followed by a closing quote, allowing a value like `\' OR
TRUE --` (which becomes `\\\' OR TRUE --`) to break out of the `r'...'`
literal. Rejecting raw string prefixes or checking `"'''" in literal` inside
the loop would close both gaps.
--
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: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]