Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 53 additions & 10 deletions src/basic_memory/repository/postgres_search_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

from basic_memory import db
from basic_memory.repository.metadata_filters import parse_metadata_filters
from basic_memory.repository.script_ngrams import analyze_script_query
from basic_memory.repository.script_ngrams import analyze_script_query, script_query_token_groups
from basic_memory.repository.search_filters import (
AFTER_DATE_ORDER_BY,
POSTGRES_FILTER_DIALECT,
Expand Down Expand Up @@ -617,6 +617,7 @@ def compile_fts_filter(
conditions.append(word_condition)

if script_query.gram_phrases:
script_token_groups = script_query_token_groups(search_text.strip())
script_tsqueries = [
" <-> ".join(f"'{gram}'" for gram in phrase) for phrase in script_query.gram_phrases
]
Expand All @@ -626,7 +627,7 @@ def compile_fts_filter(
f"({script_tsquery})" for script_tsquery in script_tsqueries
)
from_clause = _script_candidate_from_clause(scope, params)
conditions.extend(
script_conditions = [
"(search_index.script_ngrams_index_col "
f"@@ to_tsquery('simple', :script_text_{index}) OR EXISTS ("
"SELECT 1 FROM search_index_fts_chunks AS script_chunk "
Expand All @@ -636,7 +637,39 @@ def compile_fts_filter(
"AND script_chunk.script_ngrams_index_col "
f"@@ to_tsquery('simple', :script_text_{index})))"
for index in range(len(script_tsqueries))
)
]
if (
allow_relaxed
and relaxed_query_words(search_text) is not None
and len(script_token_groups) >= 2
):
# Trigger: strict AND matching found no rows for multiple eligible,
# distinct whitespace-delimited script token groups.
# Why: runs split by punctuation inside one token remain conjunctive,
# while separate user-delimited tokens can widen recall.
# Outcome: the default remains strict AND; the search runner can switch
# this one predicate to OR for its empty-result retry.
params["relaxed_script"] = False
strict_script = " AND ".join(script_conditions)
condition_by_phrase = {
phrase: script_conditions[index]
for index, phrase in enumerate(script_query.gram_phrases)
}
relaxed_groups = []
for group in script_token_groups:
group_conditions = [condition_by_phrase[phrase] for phrase in group]
group_expression = " AND ".join(group_conditions)
relaxed_groups.append(
f"({group_expression})" if len(group_conditions) > 1 else group_expression
)
relaxed_script = " OR ".join(relaxed_groups)
conditions.append(
"((CAST(:relaxed_script AS boolean) = FALSE AND "
f"({strict_script})) OR (CAST(:relaxed_script AS boolean) = TRUE AND "
f"({relaxed_script})))"
)
else:
conditions.extend(script_conditions)

# --- Fence the text candidates (#1791) ---
# Trigger: a GIN candidate join narrows the rows text conditions must check.
Expand Down Expand Up @@ -973,7 +1006,14 @@ async def execute_rows(active_session: AsyncSession, query_params: dict[str, Any
)

async def run_search(active_session: AsyncSession):
relaxed = relaxed_tsquery_text(search_text) if allow_relaxed else None
relaxed_search_text = (
analyze_script_query(search_text.strip()).word_text
if search_text and "script_text_0" in params
else search_text
)
relaxed = relaxed_tsquery_text(relaxed_search_text) if allow_relaxed else None
relaxed_script = "relaxed_script" in params
fallback_available = bool((relaxed and params.get("text")) or relaxed_script)
strict_syntax_error = False
relaxed_fallback_used = False
try:
Expand All @@ -992,12 +1032,12 @@ async def run_search(active_session: AsyncSession):
# The relaxed renderer also tokenizes punctuation safely.
# Outcome: one retry with OR-joined prefix lexemes; ts_rank still ranks
# multi-term matches first.
if relaxed and not rows and params.get("text"):
if fallback_available and not rows:
relaxed_fallback_used = True
retry_reason = "invalid syntax" if strict_syntax_error else "0 results"
logger.debug(
f"Strict Postgres FTS returned {retry_reason}; retrying relaxed FTS query "
f"strict='{search_text}' relaxed='{relaxed}'"
f"strict='{search_text}' relaxed='{relaxed}' relaxed_script='{relaxed_script}'"
)
with logfire.span(
"search.relaxed_fts_retry",
Expand All @@ -1007,10 +1047,13 @@ async def run_search(active_session: AsyncSession):
limit=limit,
offset=offset,
):
rows = await execute_rows(
active_session,
{**params, "text": relaxed, "text_exact": exact_tsquery_text(relaxed)},
)
retry_params = dict(params)
if relaxed and params.get("text"):
retry_params["text"] = relaxed
retry_params["text_exact"] = exact_tsquery_text(relaxed)
if relaxed_script:
retry_params["relaxed_script"] = True
rows = await execute_rows(active_session, retry_params)
return rows, relaxed_fallback_used

try:
Expand Down
15 changes: 15 additions & 0 deletions src/basic_memory/repository/script_ngrams.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,18 @@ def analyze_script_query(text: str) -> ScriptQuery:
word_text=word_text,
gram_phrases=gram_phrases,
)


def script_query_token_groups(text: str) -> tuple[tuple[tuple[str, ...], ...], ...]:
"""Group script runs by whitespace token and remove duplicate token groups."""
if not analyze_script_query(text).gram_phrases:
return ()

groups: list[tuple[tuple[str, ...], ...]] = []
seen_groups: set[tuple[tuple[str, ...], ...]] = set()
for token in text.split():
group = tuple(script_run_grams(run) for run in script_runs(token))
if group and group not in seen_groups:
groups.append(group)
seen_groups.add(group)
return tuple(groups)
42 changes: 35 additions & 7 deletions src/basic_memory/repository/sqlite_search_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

from basic_memory import db
from basic_memory.repository.metadata_filters import build_sqlite_json_path, parse_metadata_filters
from basic_memory.repository.script_ngrams import analyze_script_query
from basic_memory.repository.script_ngrams import analyze_script_query, script_query_token_groups
from basic_memory.repository.search_filters import (
AFTER_DATE_ORDER_BY,
SQLITE_FILTER_DIALECT,
Expand Down Expand Up @@ -241,6 +241,26 @@ def relaxed_fts_text(search_text: str | None) -> str | None:
return " OR ".join(_relaxed_fts_term(word) for word in words)


def relaxed_script_fts_text(search_text: str | None) -> str | None:
"""OR-relaxed FTS5 expression for user-delimited script phrases, or None."""
if not search_text or relaxed_query_words(search_text) is None:
return None
script_query = analyze_script_query(search_text.strip())
token_groups = script_query_token_groups(search_text.strip())
if len(token_groups) < 2:
return None

rendered_groups = []
for group in token_groups:
phrases = [f'"{" ".join(phrase)}"' for phrase in group]
group_expression = " AND ".join(phrases)
rendered_groups.append(f"({group_expression})" if len(phrases) > 1 else group_expression)

phrases = " OR ".join(rendered_groups)
script_clause = f"script_ngrams: ({phrases})"
return f" AND ({script_clause})" if script_query.word_text else script_clause


def is_fts5_syntax_error(exc: Exception) -> bool:
return "fts5: syntax error" in str(exc).lower()

Expand Down Expand Up @@ -614,6 +634,9 @@ async def run_search(active_session: AsyncSession):
result = await active_session.execute(text(sql), params)
rows = result.fetchall()
relaxed_fallback_used = False
relaxed_script = (
relaxed_script_fts_text(search_text) if allow_relaxed and not rows else None
)
# Trigger: multi-word natural-language query matched nothing under the
# default all-terms-AND semantics.
# Why: questions ("when did X do Y") rarely have every word in one
Expand All @@ -622,19 +645,24 @@ async def run_search(active_session: AsyncSession):
# Outcome: one retry with OR-joined prefix terms; bm25 still ranks
# multi-term matches first.
relaxed = relaxed_fts_text(relaxed_search_text) if allow_relaxed and not rows else None
if relaxed and params.get("text"):
if (relaxed and params.get("text")) or relaxed_script:
relaxed_fallback_used = True
params["text"] = (
f"{SQLITE_WORD_COLUMNS}: ({relaxed})" if "script_text" in params else relaxed
)
if relaxed and params.get("text"):
params["text"] = (
f"{SQLITE_WORD_COLUMNS}: ({relaxed})"
if "script_text" in params
else relaxed
)
if relaxed_script:
params["script_text"] = relaxed_script
logger.debug(
"Strict SQLite FTS returned 0 results; retrying relaxed FTS query "
f"strict='{search_text}' relaxed='{relaxed}'"
f"strict='{search_text}' relaxed='{relaxed}' relaxed_script='{relaxed_script}'"
)
with logfire.span(
"search.relaxed_fts_retry",
backend="sqlite",
token_count=len(relaxed_query_words(relaxed_search_text) or ()),
token_count=len(relaxed_query_words(search_text) or ()),
limit=limit,
offset=offset,
):
Expand Down
64 changes: 64 additions & 0 deletions tests/repository/test_script_ngrams.py
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,70 @@ async def test_sqlite_relaxed_search_keeps_word_and_script_channels_distinct(
assert results == []


@pytest.mark.asyncio
async def test_relaxed_search_ors_user_delimited_script_phrases(search_repository) -> None:
now = datetime.now(timezone.utc)
rows = [
SearchIndexRow(
project_id=search_repository.project_id,
id=1313,
type="entity",
file_path="notes/first-script-phrase.md",
title="First script phrase",
content_stems="適者",
content_snippet="適者",
permalink="notes/first-script-phrase",
created_at=now,
updated_at=now,
),
SearchIndexRow(
project_id=search_repository.project_id,
id=1314,
type="entity",
file_path="notes/second-script-phrase.md",
title="Second script phrase",
content_stems="生存",
content_snippet="生存",
permalink="notes/second-script-phrase",
created_at=now,
updated_at=now,
),
SearchIndexRow(
project_id=search_repository.project_id,
id=1315,
type="entity",
file_path="notes/mixed-script-phrase.md",
title="Mixed script phrase",
content_stems="OpenAI 適者",
content_snippet="OpenAI 適者",
permalink="notes/mixed-script-phrase",
created_at=now,
updated_at=now,
),
SearchIndexRow(
project_id=search_repository.project_id,
id=1316,
type="entity",
file_path="notes/third-script-phrase.md",
title="Third script phrase",
content_stems="不存在",
content_snippet="不存在",
permalink="notes/third-script-phrase",
created_at=now,
updated_at=now,
),
]
await search_repository.bulk_index_items(rows)

strict_results = await search_repository.search("適者 生存 不存在", allow_relaxed=False)
pure_script_results = await search_repository.search("適者 生存 不存在", allow_relaxed=True)
mixed_results = await search_repository.search("OpenAI 適者 生存", allow_relaxed=True)

assert strict_results == []
assert {result.id for result in pure_script_results} == {1313, 1314, 1315, 1316}
assert [result.id for result in mixed_results] == [1315]


@pytest.mark.asyncio
async def test_search_ranking_includes_every_script_run(search_repository) -> None:
now = datetime.now(timezone.utc)
Expand Down
41 changes: 41 additions & 0 deletions tests/repository/test_script_relaxed_fallback.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""Script fallback regressions across search backends."""

from datetime import datetime, timezone

import pytest

from basic_memory.repository.search_index_row import SearchIndexRow


@pytest.mark.asyncio
@pytest.mark.parametrize(
("query", "content"),
[
("適者/生存", "生存"),
("SPEC 16 顯示器 邊緣", "SPEC 16 邊緣"),
("OpenAI GPT 適者/生存", "OpenAI GPT 生存"),
("顯示器 邊緣/面板 磁感測", "面板"),
],
)
async def test_relaxed_search_keeps_script_token_groups_intact(
search_repository,
query: str,
content: str,
) -> None:
now = datetime.now(timezone.utc)
await search_repository.index_item(
SearchIndexRow(
project_id=search_repository.project_id,
id=2200,
type="entity",
file_path="notes/script-token-decoy.md",
title="Script token decoy",
content_stems=content,
content_snippet=content,
permalink="notes/script-token-decoy",
created_at=now,
updated_at=now,
)
)

assert await search_repository.search(query, allow_relaxed=True) == []
Loading