From 0a8504a00a47c8ca6e5e17156e38c9e7d918213c Mon Sep 17 00:00:00 2001 From: ulleo Date: Mon, 9 Nov 2026 14:56:52 +0800 Subject: [PATCH 1/4] feat: preserve complete metadata chunks for table selection --- .../versions/074_metadata_embedding.py | 29 +++ .../apps/datasource/crud/embedding_state.py | 5 + backend/apps/datasource/crud/table.py | 40 +++- .../datasource/embedding/metadata_chunks.py | 189 +++++++++++++++ .../datasource/embedding/table_embedding.py | 22 +- .../datasource/models/metadata_embedding.py | 18 ++ backend/tests/metadata_test_support.py | 27 +++ backend/tests/test_datasource_lifecycle.py | 7 +- .../test_datasource_lifecycle_integration.py | 11 +- backend/tests/test_metadata_table_chunks.py | 217 ++++++++++++++++++ .../test_metadata_table_chunks_integration.py | 151 ++++++++++++ .../test_table_parameters_integration.py | 27 ++- docs/agents/backend.md | 2 +- 13 files changed, 722 insertions(+), 23 deletions(-) create mode 100644 backend/alembic/versions/074_metadata_embedding.py create mode 100644 backend/apps/datasource/embedding/metadata_chunks.py create mode 100644 backend/apps/datasource/models/metadata_embedding.py create mode 100644 backend/tests/metadata_test_support.py create mode 100644 backend/tests/test_metadata_table_chunks.py create mode 100644 backend/tests/test_metadata_table_chunks_integration.py diff --git a/backend/alembic/versions/074_metadata_embedding.py b/backend/alembic/versions/074_metadata_embedding.py new file mode 100644 index 000000000..12bd0f3bf --- /dev/null +++ b/backend/alembic/versions/074_metadata_embedding.py @@ -0,0 +1,29 @@ +"""Create internal complete metadata embeddings without running model inference.""" + +import sqlalchemy as sa + +from alembic import op + +revision = "ed42b7f169a3" +down_revision = "c71e75fd6a30" +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + "metadata_embedding", + sa.Column("resource_type", sa.String(32), primary_key=True), + sa.Column("resource_id", sa.BigInteger(), primary_key=True), + sa.Column("format_version", sa.Integer(), nullable=False), + sa.Column("model_id", sa.Text(), nullable=False), + sa.Column("input_hash", sa.String(64), nullable=False), + sa.Column("chunk_count", sa.Integer(), nullable=False), + sa.Column("dimension", sa.Integer(), nullable=False), + sa.Column("vectors_hash", sa.String(64), nullable=False), + sa.Column("vectors", sa.Text(), nullable=False), + ) + + +def downgrade(): + op.drop_table("metadata_embedding") diff --git a/backend/apps/datasource/crud/embedding_state.py b/backend/apps/datasource/crud/embedding_state.py index cc9f159df..e20ace250 100644 --- a/backend/apps/datasource/crud/embedding_state.py +++ b/backend/apps/datasource/crud/embedding_state.py @@ -2,6 +2,7 @@ from sqlalchemy import update +from apps.datasource.embedding.metadata_chunks import invalidate_chunks from apps.datasource.models.datasource import CoreDatasource, CoreTable @@ -17,3 +18,7 @@ def invalidate_metadata(session, ds_id: int, table_ids=()): .where(CoreTable.ds_id == ds_id, CoreTable.id.in_(table_ids)) .values(embedding=None) ) + + invalidate_chunks(session, "datasource", [ds_id]) + if table_ids: + invalidate_chunks(session, "table", table_ids) diff --git a/backend/apps/datasource/crud/table.py b/backend/apps/datasource/crud/table.py index a8256c78b..f0d001b38 100644 --- a/backend/apps/datasource/crud/table.py +++ b/backend/apps/datasource/crud/table.py @@ -3,6 +3,12 @@ from sqlalchemy import select, update from apps.ai_model.embedding import EmbeddingModelCache +from apps.datasource.embedding.metadata_chunks import ( + encode_metadata, + invalidate_chunks, + publish_metadata, + read_metadata, +) from apps.datasource.embedding.utils import parse_valid_embedding from common.core.deps import SessionDep from common.core.embedding_config import load_embedding_config @@ -17,6 +23,9 @@ def delete_table_by_ds_id(session: SessionDep, id: int): + ids = [row[0] for row in session.query(CoreTable.id).filter(CoreTable.ds_id == id)] + invalidate_chunks(session, "datasource", [id]) + invalidate_chunks(session, "table", ids) session.query(CoreTable).filter(CoreTable.ds_id == id).delete( synchronize_session=False ) @@ -95,7 +104,11 @@ def _generate(session_maker, resource, ids=None, config=None): query = select(resource.id, resource.embedding).order_by(resource.id) if ids is not None: query = query.where(resource.id.in_(ids)) - pending = [key for key, vector in session.execute(query) if _missing(vector)] + pending = [ + key + for key, vector in session.execute(query) + if resource is CoreTable or _missing(vector) + ] session.commit() for key in pending: for attempt in range(3): @@ -103,13 +116,26 @@ def _generate(session_maker, resource, ids=None, config=None): lock_embedding_resource(session, resource.__tablename__, key) session.expire_all() record = session.get(resource, key) - if record is None or not _missing(record.embedding): + if record is None or ( + resource is not CoreTable and not _missing(record.embedding) + ): session.commit() break original = _resource_input(session, record) - vector = parse_valid_embedding( - EmbeddingModelCache.get_model().embed_query(original) - ) + if resource is CoreTable: + try: + read_metadata(session, "table", key, original) + session.commit() + break + except (TypeError, ValueError): + pass + vector = encode_metadata( + original, EmbeddingModelCache.get_model() + ) + else: + vector = parse_valid_embedding( + EmbeddingModelCache.get_model().embed_query(original) + ) # Writers invalidate parent first, then child, in the same # transaction as metadata. Match that order for publication. # The provider call above holds no business row locks. @@ -138,7 +164,9 @@ def _generate(session_maker, resource, ids=None, config=None): if attempt == 2: failed.append(key) continue - if _missing(current.embedding): + if resource is CoreTable: + publish_metadata(session, "table", key, original, vector) + elif _missing(current.embedding): session.execute( update(resource) .where(resource.id == key) diff --git a/backend/apps/datasource/embedding/metadata_chunks.py b/backend/apps/datasource/embedding/metadata_chunks.py new file mode 100644 index 000000000..6ea0bb648 --- /dev/null +++ b/backend/apps/datasource/embedding/metadata_chunks.py @@ -0,0 +1,189 @@ +"""Complete, tokenizer-bounded metadata representations and atomic internal storage.""" + +import copy +import hashlib +import json +from typing import Any + +from sqlalchemy import delete +from sqlalchemy.orm import Session + +from apps.datasource.embedding.utils import ( + batch_cosine_similarity, + parse_valid_embedding, +) +from apps.datasource.models.metadata_embedding import MetadataEmbedding +from common.core.config import settings + +FORMAT_VERSION = 1 + + +def fingerprint(text: str) -> str: + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def model_id() -> str: + # The deployed model is immutable for a running service (see embedding ADR). + return settings.DEFAULT_EMBEDDING_MODEL + + +def chunk_text(text: str, model: Any) -> list[str]: + """Preserve every character, preferring field lines before splitting long lines. + + HuggingFaceEmbeddings replaces newlines; SentenceTransformer's Transformer + strips and optionally lowercases text before tokenizing. Count that exact + tokenizer input including special tokens, without truncation. + """ + transformer = model._client._first_module() + limit = transformer.max_seq_length + # Fast tokenizers mutate truncation state on each call. Counting must not + # race with shared model inference (including queries and datasource jobs). + tokenizer = copy.deepcopy(transformer.tokenizer) + + def token_count(value: str) -> int: + value = value.replace("\n", " ").strip() + if transformer.do_lower_case: + value = value.lower() + return len( + tokenizer(value, truncation=False, add_special_tokens=True, verbose=False)[ + "input_ids" + ] + ) + + def fits(value: str) -> bool: + return token_count(value) <= limit + + first_line = text.splitlines(keepends=True)[0] if text else "" + context = first_line if token_count(first_line) <= min(32, limit // 4) else "" + chunks: list[str] = [] + bodies: list[str] = [] + current = "" + + def prefix() -> str: + return context if chunks else "" + + def emit(body: str) -> None: + chunks.append(prefix() + body) + bodies.append(body) + + for line in text.splitlines(keepends=True): + if fits(prefix() + current + line): + current += line + continue + if current: + emit(current) + current = "" + while line and not fits(prefix() + line): + low, high = 0, len(line) + while low < high: + middle = (low + high + 1) // 2 + if fits(prefix() + line[:middle]): + low = middle + else: + high = middle - 1 + if not low: + raise ValueError("Model cannot encode one metadata character") + emit(line[:low]) + line = line[low:] + current = line + if current: + emit(current) + if ( + not chunks + or "".join(bodies) != text + or not all(fits(chunk) for chunk in chunks) + ): + raise ValueError("Incomplete metadata input") + return chunks + + +def encode_metadata(text: str, model: Any) -> list[list[float]]: + chunks = chunk_text(text, model) + vectors: list[list[float]] = [] + for start in range(0, len(chunks), 32): + batch = chunks[start : start + 32] + result = model.embed_documents(batch) + if len(result) != len(batch): + raise ValueError("Incomplete metadata encoding") + vectors.extend(parse_valid_embedding(vector) for vector in result) + dimension = len(vectors[0]) + if any(len(vector) != dimension for vector in vectors): + raise ValueError("Inconsistent metadata dimensions") + return vectors + + +def publish_metadata( + session: Session, + resource_type: str, + resource_id: int, + text: str, + vectors: list[list[float]], +) -> None: + encoded = json.dumps(vectors, allow_nan=False) + session.merge( + MetadataEmbedding( + resource_type=resource_type, + resource_id=resource_id, + format_version=FORMAT_VERSION, + model_id=model_id(), + input_hash=fingerprint(text), + chunk_count=len(vectors), + dimension=len(vectors[0]), + vectors_hash=fingerprint(encoded), + vectors=encoded, + ) + ) + + +def read_metadata( + session: Session, resource_type: str, resource_id: int, text: str +) -> list[list[float]]: + record = session.get(MetadataEmbedding, (resource_type, resource_id)) + if ( + record is None + or record.format_version != FORMAT_VERSION + or record.model_id != model_id() + or record.input_hash != fingerprint(text) + or record.chunk_count < 1 + or fingerprint(record.vectors) != record.vectors_hash + ): + raise ValueError("Missing or stale metadata representation") + vectors = json.loads(record.vectors) + if not isinstance(vectors, list) or len(vectors) != record.chunk_count: + raise ValueError("Incomplete metadata representation") + vectors = [parse_valid_embedding(vector) for vector in vectors] + if any(len(vector) != record.dimension for vector in vectors): + raise ValueError("Inconsistent metadata dimensions") + return vectors + + +def invalidate_chunks(session: Session, resource_type: str, ids: list[int]) -> None: + session.execute( + delete(MetadataEmbedding).where( + MetadataEmbedding.resource_type == resource_type, + MetadataEmbedding.resource_id.in_(ids), + ) + ) + + +def table_scores( + session: Session, tables: list[dict[str, Any]], query_embedding: Any +) -> list[float]: + # Only caller-authorized IDs are loaded. Fingerprints use persisted metadata, + # not the permission-filtered schema rendered for this particular user. + from apps.datasource.crud.table import _table_input + from apps.datasource.models.datasource import CoreTable + + query = parse_valid_embedding(query_embedding) + scores = [] + for candidate in tables: + table = session.get(CoreTable, candidate["id"]) + if table is None: + raise ValueError("Missing metadata table") + vectors = read_metadata( + session, "table", table.id, _table_input(session, table) + ) + if any(len(vector) != len(query) for vector in vectors): + raise ValueError("Query and metadata dimensions differ") + scores.append(float(max(batch_cosine_similarity(query, vectors)))) + return scores diff --git a/backend/apps/datasource/embedding/table_embedding.py b/backend/apps/datasource/embedding/table_embedding.py index 87e503071..c255c39d8 100644 --- a/backend/apps/datasource/embedding/table_embedding.py +++ b/backend/apps/datasource/embedding/table_embedding.py @@ -6,6 +6,7 @@ import traceback from apps.ai_model.embedding import EmbeddingModelCache +from apps.datasource.embedding.metadata_chunks import table_scores from apps.datasource.embedding.utils import ( batch_cosine_similarity, cosine_similarity, @@ -228,16 +229,19 @@ def calc_keyword_score( return round(best_score * match_rate, 2) -def _score_table_vectors(tables: list[dict], query_embedding) -> int: +def _score_table_vectors(tables: list[dict], query_embedding, session=None) -> int: """Validate the complete candidate set before publishing any vector scores.""" - embeddings = [parse_valid_embedding(table.get('embedding')) for table in tables] - similarities = batch_cosine_similarity(parse_valid_embedding(query_embedding), embeddings) + if session is not None: + similarities = table_scores(session, tables, query_embedding) + else: + embeddings = [parse_valid_embedding(table.get('embedding')) for table in tables] + similarities = batch_cosine_similarity(parse_valid_embedding(query_embedding), embeddings) for table, similarity in zip(tables, similarities, strict=True): table['cosine_similarity'] = float(similarity) - return len(embeddings) + return len(tables) -def calc_table_embedding(tables: list[dict], question: str, session=None, oid: int = None, +def calc_table_embedding(tables: list[dict], question: str, session=None, oid: int = None, # noqa: ARG001 - retained for caller compatibility keywords: str = None, *, config: EmbeddingConfig = None): """使用向量相似度和关键词匹配的融合评分计算表的相关性分数。 @@ -260,7 +264,7 @@ def calc_table_embedding(tables: list[dict], question: str, session=None, oid: i config = load_embedding_config(session) if not keywords or not (config.keyword_enabled if config else settings.TABLE_EMBEDDING_KEYWORD_ENABLED): # 回退到纯向量匹配 - return _calc_vector_only(tables, question, config=config) + return _calc_vector_only(tables, question, config=config, session=session) _list = [] for table in tables: @@ -288,7 +292,7 @@ def calc_table_embedding(tables: list[dict], question: str, session=None, oid: i SQLBotLogUtil.info(f"[perf] embed_query 耗时 {t1 - t0:.3f}s") # A partial vector set must never exclude otherwise eligible tables. - vector_count = _score_table_vectors(_list, q_embedding) + vector_count = _score_table_vectors(_list, q_embedding, session=session) t2 = time.time() SQLBotLogUtil.info(f"[perf] 向量相似度计算耗时 {t2 - t1:.3f}s,共 {vector_count} 张表") @@ -352,7 +356,7 @@ def calc_table_embedding(tables: list[dict], question: str, session=None, oid: i return _select_tables(tables, question, apply_limit=False) -def _calc_vector_only(tables: list[dict], question: str, *, config: EmbeddingConfig = None): +def _calc_vector_only(tables: list[dict], question: str, *, config: EmbeddingConfig = None, session=None): """Rank by vector similarity while retaining explicitly mentioned tables.""" _list = [] for table in tables: @@ -372,7 +376,7 @@ def _calc_vector_only(tables: list[dict], question: str, *, config: EmbeddingCon start_time = time.time() q_embedding = model.embed_query(question) - vector_count = _score_table_vectors(_list, q_embedding) + vector_count = _score_table_vectors(_list, q_embedding, session=session) _list.sort(key=lambda x: x['cosine_similarity'], reverse=True) _list = _select_tables(_list, question, count=config.table_count if config else None) diff --git a/backend/apps/datasource/models/metadata_embedding.py b/backend/apps/datasource/models/metadata_embedding.py new file mode 100644 index 000000000..5ff133155 --- /dev/null +++ b/backend/apps/datasource/models/metadata_embedding.py @@ -0,0 +1,18 @@ +"""Internal metadata representations; deliberately separate from management DTOs.""" + +from sqlalchemy import BigInteger, Column, Text +from sqlmodel import Field, SQLModel + + +class MetadataEmbedding(SQLModel, table=True): + __tablename__ = "metadata_embedding" + + resource_type: str = Field(primary_key=True, max_length=32) + resource_id: int = Field(sa_column=Column(BigInteger, primary_key=True)) + format_version: int + model_id: str = Field(sa_column=Column(Text, nullable=False)) + input_hash: str = Field(max_length=64) + chunk_count: int + dimension: int + vectors_hash: str = Field(max_length=64) + vectors: str = Field(sa_column=Column(Text, nullable=False)) diff --git a/backend/tests/metadata_test_support.py b/backend/tests/metadata_test_support.py new file mode 100644 index 000000000..0cfda2627 --- /dev/null +++ b/backend/tests/metadata_test_support.py @@ -0,0 +1,27 @@ +"""Deterministic external embedding adapter and public metadata reader for tests.""" + +from types import SimpleNamespace + + +def metadata_model(vector=None, *, embed=None, limit=128): + encode = embed or (lambda _value: vector or [1.0, 0.0]) + return SimpleNamespace( + embed_query=encode, + embed_documents=lambda texts: [encode(text) for text in texts], + _client=SimpleNamespace( + _first_module=lambda: SimpleNamespace( + max_seq_length=limit, + do_lower_case=False, + tokenizer=lambda text, **_kwargs: {"input_ids": [0, *list(text), 1]}, + ) + ), + ) + + +def read_table_vectors(session, table_id): + from apps.datasource.crud.table import _table_input + from apps.datasource.embedding.metadata_chunks import read_metadata + from apps.datasource.models.datasource import CoreTable + + table = session.get(CoreTable, table_id) + return read_metadata(session, "table", table_id, _table_input(session, table)) diff --git a/backend/tests/test_datasource_lifecycle.py b/backend/tests/test_datasource_lifecycle.py index 4da7c702c..21472c5ef 100644 --- a/backend/tests/test_datasource_lifecycle.py +++ b/backend/tests/test_datasource_lifecycle.py @@ -4,6 +4,7 @@ import pytest from fastapi.testclient import TestClient +from metadata_test_support import metadata_model, read_table_vectors from sqlalchemy import JSON, Integer, MetaData from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.pool import StaticPool @@ -14,6 +15,7 @@ from apps.datasource.crud.datasource import get_ds, updateField from apps.datasource.crud.table import get_tables_by_ds_id from apps.datasource.models.datasource import CoreDatasource, CoreField, CoreTable +from apps.datasource.models.metadata_embedding import MetadataEmbedding from common.core.config import settings from common.utils import embedding_threads @@ -29,6 +31,7 @@ def environment(monkeypatch): table.c.id.type = Integer() if model is CoreDatasource: table.c.table_relation.type = JSON() + MetadataEmbedding.__table__.to_metadata(metadata) metadata.create_all(database) maker = scoped_session(sessionmaker(bind=database, class_=Session)) jobs = [] @@ -89,7 +92,7 @@ def test_queued_metadata_task_observes_switch_at_actual_start(environment, monke monkeypatch.setattr( EmbeddingModelCache, "get_model", - lambda: SimpleNamespace(embed_query=lambda _: [0.6, 0.8]), + lambda: metadata_model([0.6, 0.8]), ) assert ( save(client, [{"pkey": "embedding.table_enabled", "pval": True}]).status_code @@ -98,7 +101,7 @@ def test_queued_metadata_task_observes_switch_at_actual_start(environment, monke run_jobs(jobs) with Session(database) as session: assert get_ds(session, 1).embedding == "[0.6, 0.8]" - assert get_tables_by_ds_id(session, 1)[0].embedding == "[0.6, 0.8]" + assert read_table_vectors(session, 1) == [[0.6, 0.8]] @pytest.mark.parametrize("value", [0, 1, "yes", "0", None, [], 0.5]) diff --git a/backend/tests/test_datasource_lifecycle_integration.py b/backend/tests/test_datasource_lifecycle_integration.py index 8203e988a..713f8190b 100644 --- a/backend/tests/test_datasource_lifecycle_integration.py +++ b/backend/tests/test_datasource_lifecycle_integration.py @@ -3,6 +3,7 @@ from concurrent.futures import ThreadPoolExecutor import pytest +from metadata_test_support import metadata_model, read_table_vectors from sqlalchemy.orm import scoped_session, sessionmaker from sqlmodel import Session from test_embedding_parameters import save, values @@ -12,6 +13,8 @@ ) from test_table_parameters_integration import table_environment # noqa: F401 +from apps.datasource.embedding.metadata_chunks import invalidate_chunks + @pytest.fixture def lifecycle_environment(table_environment, monkeypatch): # noqa: F811 @@ -361,7 +364,7 @@ def embed(value): return [0, 1] if "latest content" in value else [1, 0] monkeypatch.setattr( - EmbeddingModelCache, "get_model", lambda: SimpleNamespace(embed_query=embed) + EmbeddingModelCache, "get_model", lambda: metadata_model(embed=embed) ) with Session(database) as session: table = next(t for t in get_tables_by_ds_id(session, ds_id) if t.checked) @@ -370,6 +373,7 @@ def embed(value): field_id = field.id if resource == "table": table.embedding = None + invalidate_chunks(session, "table", [table_id]) else: session.get(CoreDatasource, ds_id).embedding = None session.commit() @@ -422,7 +426,10 @@ def embed(value): if resource == "table" else crud.get_ds(session, ds_id) ) - assert result.embedding == "[0.0, 1.0]" + if resource == "table": + assert read_table_vectors(session, table_id) == [[0, 1]] + else: + assert result.embedding == "[0.0, 1.0]" if resource == "table": assert crud.get_ds(session, ds_id).embedding is None assert "latest content" in inputs[-1] diff --git a/backend/tests/test_metadata_table_chunks.py b/backend/tests/test_metadata_table_chunks.py new file mode 100644 index 000000000..76c55a7b3 --- /dev/null +++ b/backend/tests/test_metadata_table_chunks.py @@ -0,0 +1,217 @@ +# ruff: noqa: F811 +"""Metadata save, generation and candidate selection at the service boundary.""" + +from types import SimpleNamespace + +from sqlmodel import Session +from test_datasource_lifecycle import environment, run_jobs # noqa: F401 + +from apps.ai_model.embedding import EmbeddingModelCache +from apps.datasource.crud.datasource import updateField +from apps.datasource.crud.table import get_tables_by_ds_id +from apps.datasource.embedding.table_embedding import calc_table_embedding +from apps.datasource.models.datasource import CoreField +from common.core.embedding_config import load_embedding_config + + +class BoundaryModel: + """Offline provider whose preprocessor truncates at a known input boundary.""" + + def __init__(self): + self.inputs = [] + self._client = SimpleNamespace( + _first_module=lambda: SimpleNamespace( + max_seq_length=48, + do_lower_case=False, + tokenizer=lambda text, **kwargs: {"input_ids": [0, *list(text), 1]}, + ) + ) + + def embed_documents(self, texts): + self.inputs.extend(texts) + return [[1.0, 0.0] if "TAIL" in text else [0.0, 1.0] for text in texts] + + def embed_query(self, text): + return [1.0, 0.0] + + +def test_saved_wide_table_publishes_all_chunks_and_uses_tail_for_selection( + environment, monkeypatch +): + from apps.datasource.models.metadata_embedding import MetadataEmbedding + + database, _client, jobs = environment + MetadataEmbedding.__table__.create(database, checkfirst=True) + model = BoundaryModel() + monkeypatch.setattr(EmbeddingModelCache, "get_model", lambda: model) + with Session(database) as session: + for index in range(2, 122): + session.add( + CoreField( + id=index, + ds_id=1, + table_id=1, + field_name=f"field_{index}", + field_type="INT", + field_index=index, + ) + ) + session.commit() + updateField( + session, + CoreField(id=121, ds_id=1, table_id=1, checked=True, custom_comment="TAIL"), + ) + run_jobs(jobs) + assert len(model.inputs) > 1 + assert all(len(text.replace("\n", " ").strip()) + 2 <= 48 for text in model.inputs) + assert "TAIL" in "".join(model.inputs) + assert all(f"field_{index}" in "".join(model.inputs) for index in range(2, 122)) + with Session(database) as session: + tables = get_tables_by_ds_id(session, 1) + assert "vectors" not in tables[0].model_dump() + result = calc_table_embedding( + [{"id": 1, "table_name": "sales", "schema_table": "sales"}], + "tail synonym", + session=session, + config=load_embedding_config(session), + ) + assert result[0]["cosine_similarity"] == 1.0 + assert "chunks" not in result[0] + + +def test_chunk_sets_rank_distinct_allowed_tables_and_invalid_sets_skip_pruning( + environment, monkeypatch +): + from dataclasses import replace + + from apps.datasource.crud.table import save_table_embedding + from apps.datasource.models.datasource import CoreTable + from apps.datasource.models.metadata_embedding import MetadataEmbedding + from common.utils import embedding_threads + + database, _client, _jobs = environment + model = BoundaryModel() + monkeypatch.setattr(EmbeddingModelCache, "get_model", lambda: model) + with Session(database) as session: + for key in range(2, 14): + session.add( + CoreTable( + id=key, + ds_id=1, + table_name=f"table_{key}", + custom_comment=("TAIL" if key == 12 else "ordinary") + " note" * 30, + ) + ) + session.commit() + save_table_embedding(embedding_threads.session_maker, list(range(1, 14))) + candidates = [ + {"id": key, "table_name": f"table_{key}", "schema_table": f"table_{key}"} + for key in range(1, 13) + ] + with Session(database) as session: + config = replace(load_embedding_config(session), table_count=10) + result = calc_table_embedding( + candidates, "synonym", session=session, config=config + ) + assert len(result) == len({table["id"] for table in result}) == 10 + assert result[0]["id"] == 12 + assert 13 not in {table["id"] for table in result} + # A missing block must invalidate the whole layer, even if others match. + representation = session.get(MetadataEmbedding, ("table", 1)) + representation.chunk_count += 1 + session.commit() + result = calc_table_embedding( + candidates, "synonym", session=session, config=config + ) + assert {table["id"] for table in result} == set(range(1, 13)) + + +def test_edit_invalidates_complete_representation_even_with_switch_disabled( + environment, monkeypatch +): + from dataclasses import replace + + from test_embedding_parameters import save + + from apps.datasource.crud.table import save_table_embedding + from apps.datasource.models.datasource import CoreTable + from common.utils import embedding_threads + + database, client, _jobs = environment + monkeypatch.setattr(EmbeddingModelCache, "get_model", lambda: BoundaryModel()) + with Session(database) as session: + session.add(CoreTable(id=2, ds_id=1, table_name="other")) + session.commit() + save_table_embedding(embedding_threads.session_maker, [1, 2]) + candidates = [ + {"id": key, "table_name": str(key), "schema_table": str(key)} for key in (1, 2) + ] + with Session(database) as session: + config = replace(load_embedding_config(session), table_count=1) + assert ( + len(calc_table_embedding(candidates, "q", session=session, config=config)) + == 1 + ) + assert ( + save(client, [{"pkey": "embedding.table_enabled", "pval": False}]).status_code + == 200 + ) + with Session(database) as session: + updateField( + session, + CoreField( + id=1, + ds_id=1, + table_id=1, + checked=True, + custom_comment="changed while disabled", + ), + ) + assert ( + len(calc_table_embedding(candidates, "q", session=session, config=config)) + == 2 + ) + + +def test_incomplete_provider_batch_is_not_published_and_later_task_recovers( + environment, monkeypatch +): + import pytest + from metadata_test_support import read_table_vectors + + from apps.datasource.crud.table import save_table_embedding + from common.utils import embedding_threads + from common.utils.embedding_lifecycle import EmbeddingGenerationError + + database, _client, _jobs = environment + model = BoundaryModel() + with Session(database) as session: + for index in range(2, 122): + session.add( + CoreField( + id=index, + ds_id=1, + table_id=1, + field_name=f"field_{index}", + field_type="INT", + field_index=index, + ) + ) + session.commit() + original = model.embed_documents + + def incomplete(texts): + vectors = original(texts) + return vectors if len(model.inputs) <= 32 else vectors[:-1] + + model.embed_documents = incomplete + monkeypatch.setattr(EmbeddingModelCache, "get_model", lambda: model) + with pytest.raises(EmbeddingGenerationError): + save_table_embedding(embedding_threads.session_maker, [1]) + with Session(database) as session: + with pytest.raises(ValueError): + read_table_vectors(session, 1) + model.embed_documents = original + save_table_embedding(embedding_threads.session_maker, [1]) + with Session(database) as session: + assert len(read_table_vectors(session, 1)) > 32 diff --git a/backend/tests/test_metadata_table_chunks_integration.py b/backend/tests/test_metadata_table_chunks_integration.py new file mode 100644 index 000000000..c273f3221 --- /dev/null +++ b/backend/tests/test_metadata_table_chunks_integration.py @@ -0,0 +1,151 @@ +# ruff: noqa: F811 +"""Opt-in real tokenizer/model + PostgreSQL table-save acceptance. + +Uses only synthetic metadata and the local deployed model. Run with the same +explicit disposable-PostgreSQL opt-in as the other embedding integration tests. +""" + +from concurrent.futures import ThreadPoolExecutor +from types import SimpleNamespace + +import pytest +from metadata_test_support import read_table_vectors +from sqlalchemy.orm import scoped_session, sessionmaker +from sqlmodel import Session +from test_embedding_parameters_integration import ( # noqa: F401 + knowledge_environment, + pytestmark, +) +from test_table_parameters_integration import table_environment # noqa: F401 + +from apps.ai_model.embedding import EmbeddingModelCache +from apps.datasource.crud.datasource import updateField +from apps.datasource.crud.table import _table_input +from apps.datasource.embedding.table_embedding import calc_table_embedding +from apps.datasource.models.datasource import CoreField, CoreTable +from common.core.embedding_config import load_embedding_config +from common.utils import embedding_threads + + +@pytest.fixture(scope="module") +def local_model(): + import torch + + torch.set_num_threads(4) + return EmbeddingModelCache._new_instance() + + +@pytest.mark.parametrize("shape", ["short", "wide", "long_comment", "long_identifier"]) +def test_saved_metadata_covers_all_actual_model_inputs( + table_environment, monkeypatch, local_model, shape +): + database, _client, ds_id = table_environment + sessions = scoped_session(sessionmaker(bind=database, class_=Session)) + monkeypatch.setattr(embedding_threads, "session_maker", sessions) + inputs, futures = [], [] + + def embed_documents(texts): + inputs.extend(texts) + return local_model.embed_documents(texts) + + monkeypatch.setattr( + EmbeddingModelCache, + "get_model", + lambda: SimpleNamespace( + _client=local_model._client, + embed_documents=embed_documents, + embed_query=local_model.embed_query, + ), + ) + with ThreadPoolExecutor(max_workers=2) as executor: + + def submit(function, *args): + future = executor.submit(function, *args) + futures.append(future) + return future + + monkeypatch.setattr( + embedding_threads, "executor", SimpleNamespace(submit=submit) + ) + with Session(database) as session: + table = session.query(CoreTable).filter(CoreTable.ds_id == ds_id).first() + table_id = table.id + table.table_name = "业务表" + ( + "超长表标识" * 160 if shape == "long_identifier" else "" + ) + session.add(table) + session.query(CoreField).filter(CoreField.table_id == table_id).delete() + for index in range(120 if shape == "wide" else 1): + field = CoreField( + ds_id=ds_id, + table_id=table_id, + field_index=index, + field_name=f"字段{index}" + + ("超长字段标识" * 160 if shape == "long_identifier" else ""), + field_type="INT", + custom_comment=f"业务指标{index}", + ) + session.add(field) + session.flush() + field_id = field.id + session.commit() + updateField( + session, + CoreField( + id=field_id, + ds_id=ds_id, + table_id=table_id, + checked=True, + custom_comment="TAIL尾部指标" + + ("超长字段注释" * 300 if shape == "long_comment" else ""), + ), + ) + original = _table_input(session, session.get(CoreTable, table_id)) + for future in futures: + future.result(timeout=30) + assert inputs + first = local_model._client._first_module() + first_line = original.splitlines(keepends=True)[0] + # Remove only the permitted repeated table context to reconstruct the body. + reconstructed = inputs[0] + "".join( + chunk[len(first_line) :] if chunk.startswith(first_line) else chunk + for chunk in inputs[1:] + ) + assert reconstructed == original + for chunk in inputs: + prepared = chunk.replace("\n", " ") + actual = local_model._client.tokenize([prepared])["input_ids"][0].tolist() + complete = first.tokenizer(prepared, add_special_tokens=True, truncation=False)[ + "input_ids" + ] + assert actual == complete + assert len(actual) <= first.max_seq_length + if shape != "short": + assert len(inputs) > 1 + assert ( + len( + first.tokenizer(original.replace("\n", " "), truncation=False)[ + "input_ids" + ] + ) + > first.max_seq_length + ) + assert ( + len( + local_model._client.tokenize([original.replace("\n", " ")])[ + "input_ids" + ][0] + ) + == first.max_seq_length + ) + with Session(database) as session: + assert len(read_table_vectors(session, table_id)) == len(inputs) + selected = calc_table_embedding( + [{"id": table_id, "table_name": "业务表", "schema_table": "allowed"}], + "TAIL尾部指标", + session=session, + config=load_embedding_config(session), + ) + assert selected[0]["cosine_similarity"] > 0 + assert "vectors" not in session.get(CoreTable, table_id).model_dump() + sessions.remove() diff --git a/backend/tests/test_table_parameters_integration.py b/backend/tests/test_table_parameters_integration.py index 44b640c23..86d4f7851 100644 --- a/backend/tests/test_table_parameters_integration.py +++ b/backend/tests/test_table_parameters_integration.py @@ -18,7 +18,10 @@ from apps.ai_model.model_factory import LLMConfig from apps.chat.models.chat_model import Chat, ChatFinishStep, ChatQuestion, ChatRecord from apps.chat.task.llm import LLMService +from apps.datasource.crud.table import _table_input +from apps.datasource.embedding.metadata_chunks import fingerprint, publish_metadata from apps.datasource.models.datasource import CoreDatasource, CoreField, CoreTable +from apps.datasource.models.metadata_embedding import MetadataEmbedding from apps.datasource.utils.utils import aes_encrypt from apps.terminology.models.terminology_model import Terminology from common.core.config import settings @@ -27,7 +30,7 @@ @pytest.fixture def table_environment(knowledge_environment, monkeypatch): # noqa: F811 database, client, _chat_id = knowledge_environment - for model in (CoreDatasource, CoreTable, CoreField, DsRules): + for model in (CoreDatasource, CoreTable, CoreField, DsRules, MetadataEmbedding): model.__table__.create(database) monkeypatch.setattr(settings, "TABLE_EMBEDDING_ENABLED", True) monkeypatch.setattr(settings, "TABLE_EMBEDDING_COUNT", 10) @@ -74,6 +77,15 @@ def table_environment(knowledge_environment, monkeypatch): # noqa: F811 field_index=1, ) ) + session.flush() + for table in session.query(CoreTable).all(): + publish_metadata( + session, + "table", + table.id, + _table_input(session, table), + [json.loads(table.embedding)], + ) session.commit() yield database, client, ds_id sessions.remove() @@ -230,8 +242,13 @@ def test_incomplete_table_vectors_preserve_all_eligible_context( table = ( session.query(CoreTable).filter(CoreTable.table_name == "sales_alpha").one() ) - table.embedding = bad_vector - session.add(table) + record = session.get(MetadataEmbedding, ("table", table.id)) + try: + record.vectors = json.dumps([json.loads(bad_vector)]) + except (TypeError, ValueError): + record.vectors = "broken" + record.vectors_hash = fingerprint(record.vectors) + session.add(record) session.commit() schema = run(task(database, ds_id)) assert all(name in schema for name in ("sales_alpha", "vector_beta", "other_gamma")) @@ -583,6 +600,10 @@ def test_column_permissions_also_bound_relation_context(table_environment): } ] session.add(ds) + session.flush() + publish_metadata( + session, "table", beta.id, _table_input(session, beta), [[1, 0]] + ) session.commit() schema = run(task(database, ds_id, user_id=2)) assert "vector_beta" in schema and "secret_join" not in schema diff --git a/docs/agents/backend.md b/docs/agents/backend.md index 6dca5312b..c667ac336 100644 --- a/docs/agents/backend.md +++ b/docs/agents/backend.md @@ -55,7 +55,7 @@ Endpoint 命名沿既有风格: - 事务提交通常发生在 CRUD/service 边界;API handler 不要随意中途 commit。 - embedding、缓存清理或后台任务沿用当前领域的线程任务模式,不在请求路径中阻塞等待长任务。 - 知识向量任务通过 `common/utils/embedding_lifecycle.py` 在实际工作线程开始时读取持久化配置;术语主词/同义词与 SQL 示例问题变化必须在业务事务内使受影响向量失效。生成任务使用按资源的 PostgreSQL 事务 advisory lock、锁后重读和输入条件写回,不能用进程内锁或无条件写回替代。失败向量保持空值,有限重试失败后报告异常,后续资源任务、重新开启和进程启动均可重试。 -- 表与数据源向量任务入口在 `apps/datasource/crud/table.py`,复用上述资源锁并兼容 JSON 向量。元数据写入先按父数据源、子表顺序在同一事务内使向量失效(`embedding_state.py`);生成期间不持有业务行锁,发布前按相同顺序锁行、重读并比较完整输入,防止旧结果覆盖修改。启动与重新开启扫描修复缺失或无效向量,保留有效向量;启动补齐不使用进程生命周期级单次锁。 +- 表与数据源向量任务入口在 `apps/datasource/crud/table.py`,复用上述资源锁并兼容 JSON 向量。元数据写入先按父数据源、子表顺序在同一事务内使向量失效(`embedding_state.py`);生成期间不持有业务行锁,发布前按相同顺序锁行、重读并比较完整输入,防止旧结果覆盖修改。启动与重新开启扫描修复缺失或无效向量,保留有效向量;启动补齐不使用进程生命周期级单次锁。 表的完整分块表示保存在独立 `metadata_embedding` 内部表(`apps/datasource/embedding/metadata_chunks.py`),包含模型、格式版本、输入指纹及完整性信息,不进入管理 DTO。表读取依据当前持久化元数据校验完整集合后取最大块分数;旧单向量不作为新格式完成标记。长度检查使用独立 tokenizer 副本,避免修改共享推理 tokenizer 的截断状态。 ## 异步与阻塞 From e5cbb2f7da0f3e62ee4ccc4dd2db5fd8ede8bd92 Mon Sep 17 00:00:00 2001 From: ulleo Date: Mon, 9 Nov 2026 15:08:16 +0800 Subject: [PATCH 2/4] feat: rank datasource candidates with complete metadata chunks --- backend/apps/datasource/crud/table.py | 58 +--- .../apps/datasource/embedding/ds_embedding.py | 25 +- backend/tests/metadata_test_support.py | 11 + backend/tests/test_datasource_lifecycle.py | 8 +- .../tests/test_metadata_datasource_chunks.py | 147 +++++++++++ ..._metadata_datasource_chunks_integration.py | 249 ++++++++++++++++++ .../test_metadata_table_chunks_integration.py | 103 +++++--- .../test_table_parameters_integration.py | 23 +- 8 files changed, 529 insertions(+), 95 deletions(-) create mode 100644 backend/tests/test_metadata_datasource_chunks.py create mode 100644 backend/tests/test_metadata_datasource_chunks_integration.py diff --git a/backend/apps/datasource/crud/table.py b/backend/apps/datasource/crud/table.py index f0d001b38..d9466197f 100644 --- a/backend/apps/datasource/crud/table.py +++ b/backend/apps/datasource/crud/table.py @@ -1,6 +1,4 @@ -import json - -from sqlalchemy import select, update +from sqlalchemy import select from apps.ai_model.embedding import EmbeddingModelCache from apps.datasource.embedding.metadata_chunks import ( @@ -9,7 +7,6 @@ publish_metadata, read_metadata, ) -from apps.datasource.embedding.utils import parse_valid_embedding from common.core.deps import SessionDep from common.core.embedding_config import load_embedding_config from common.utils.embedding_lifecycle import ( @@ -50,14 +47,6 @@ def update_table(session: SessionDep, item: CoreTable): session.commit() -def _missing(vector): - try: - parse_valid_embedding(vector) - return False - except (TypeError, ValueError): - return True - - def _table_input(session, table): comment = (table.custom_comment or table.table_comment or "").strip() result = ( @@ -101,14 +90,11 @@ def _generate(session_maker, resource, ids=None, config=None): config = config or load_embedding_config(session) if not config.table_enabled: return - query = select(resource.id, resource.embedding).order_by(resource.id) + query = select(resource.id).order_by(resource.id) if ids is not None: query = query.where(resource.id.in_(ids)) - pending = [ - key - for key, vector in session.execute(query) - if resource is CoreTable or _missing(vector) - ] + pending = list(session.execute(query).scalars()) + resource_type = "table" if resource is CoreTable else "datasource" session.commit() for key in pending: for attempt in range(3): @@ -116,26 +102,17 @@ def _generate(session_maker, resource, ids=None, config=None): lock_embedding_resource(session, resource.__tablename__, key) session.expire_all() record = session.get(resource, key) - if record is None or ( - resource is not CoreTable and not _missing(record.embedding) - ): + if record is None: session.commit() break original = _resource_input(session, record) - if resource is CoreTable: - try: - read_metadata(session, "table", key, original) - session.commit() - break - except (TypeError, ValueError): - pass - vector = encode_metadata( - original, EmbeddingModelCache.get_model() - ) - else: - vector = parse_valid_embedding( - EmbeddingModelCache.get_model().embed_query(original) - ) + try: + read_metadata(session, resource_type, key, original) + session.commit() + break + except (TypeError, ValueError): + pass + vector = encode_metadata(original, EmbeddingModelCache.get_model()) # Writers invalidate parent first, then child, in the same # transaction as metadata. Match that order for publication. # The provider call above holds no business row locks. @@ -164,16 +141,7 @@ def _generate(session_maker, resource, ids=None, config=None): if attempt == 2: failed.append(key) continue - if resource is CoreTable: - publish_metadata(session, "table", key, original, vector) - elif _missing(current.embedding): - session.execute( - update(resource) - .where(resource.id == key) - .values( - embedding=json.dumps([float(value) for value in vector]) - ) - ) + publish_metadata(session, resource_type, key, original, vector) session.commit() break except Exception: diff --git a/backend/apps/datasource/embedding/ds_embedding.py b/backend/apps/datasource/embedding/ds_embedding.py index d40478f87..9c008a3c9 100644 --- a/backend/apps/datasource/embedding/ds_embedding.py +++ b/backend/apps/datasource/embedding/ds_embedding.py @@ -3,7 +3,11 @@ import traceback from apps.ai_model.embedding import EmbeddingModelCache -from apps.datasource.embedding.utils import cosine_similarity, parse_valid_embedding +from apps.datasource.embedding.metadata_chunks import read_metadata +from apps.datasource.embedding.utils import ( + batch_cosine_similarity, + parse_valid_embedding, +) from apps.datasource.models.datasource import CoreDatasource from apps.system.crud.assistant import AssistantOutDs from common.core.deps import CurrentAssistant, SessionDep @@ -27,21 +31,34 @@ def get_ds_embedding( if not config.table_enabled or len(_ds_list) <= 1: return _ds_list try: + from apps.datasource.crud.table import _resource_input + vectors = [] for candidate in _ds_list: datasource = session.get(CoreDatasource, candidate.get("id")) + if datasource is None: + raise ValueError("Missing metadata datasource") vectors.append( - parse_valid_embedding(datasource.embedding if datasource else None) + read_metadata( + session, + "datasource", + datasource.id, + _resource_input(session, datasource), + ) ) query = parse_valid_embedding( EmbeddingModelCache.get_model().embed_query(question) ) + if any(len(vector) != len(query) for chunks in vectors for vector in chunks): + raise ValueError("Query and metadata dimensions differ") ranked = sorted( zip(_ds_list, vectors, strict=True), - key=lambda item: cosine_similarity(query, item[1]), + key=lambda item: float(max(batch_cosine_similarity(query, item[1]))), reverse=True, ) - selected = [candidate for candidate, _vector in ranked[: config.datasource_count]] + selected = [ + candidate for candidate, _vector in ranked[: config.datasource_count] + ] SQLBotLogUtil.info( f"[embedding] stage=datasource action=vector_selection " f"candidate_count={len(_ds_list)} result_count={len(selected)} " diff --git a/backend/tests/metadata_test_support.py b/backend/tests/metadata_test_support.py index 0cfda2627..48bace336 100644 --- a/backend/tests/metadata_test_support.py +++ b/backend/tests/metadata_test_support.py @@ -25,3 +25,14 @@ def read_table_vectors(session, table_id): table = session.get(CoreTable, table_id) return read_metadata(session, "table", table_id, _table_input(session, table)) + + +def read_datasource_vectors(session, datasource_id): + from apps.datasource.crud.table import _resource_input + from apps.datasource.embedding.metadata_chunks import read_metadata + from apps.datasource.models.datasource import CoreDatasource + + datasource = session.get(CoreDatasource, datasource_id) + return read_metadata( + session, "datasource", datasource_id, _resource_input(session, datasource) + ) diff --git a/backend/tests/test_datasource_lifecycle.py b/backend/tests/test_datasource_lifecycle.py index 21472c5ef..a88209481 100644 --- a/backend/tests/test_datasource_lifecycle.py +++ b/backend/tests/test_datasource_lifecycle.py @@ -4,7 +4,11 @@ import pytest from fastapi.testclient import TestClient -from metadata_test_support import metadata_model, read_table_vectors +from metadata_test_support import ( + metadata_model, + read_datasource_vectors, + read_table_vectors, +) from sqlalchemy import JSON, Integer, MetaData from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.pool import StaticPool @@ -100,7 +104,7 @@ def test_queued_metadata_task_observes_switch_at_actual_start(environment, monke ) run_jobs(jobs) with Session(database) as session: - assert get_ds(session, 1).embedding == "[0.6, 0.8]" + assert read_datasource_vectors(session, 1) == [[0.6, 0.8]] assert read_table_vectors(session, 1) == [[0.6, 0.8]] diff --git a/backend/tests/test_metadata_datasource_chunks.py b/backend/tests/test_metadata_datasource_chunks.py new file mode 100644 index 000000000..eae4b781b --- /dev/null +++ b/backend/tests/test_metadata_datasource_chunks.py @@ -0,0 +1,147 @@ +# ruff: noqa: F811 +"""Datasource save/generate/preselect contracts with an offline provider boundary.""" + +from dataclasses import replace + +import pytest +from sqlmodel import Session +from test_datasource_lifecycle import environment, run_jobs # noqa: F401 +from test_metadata_table_chunks import BoundaryModel + +from apps.ai_model.embedding import EmbeddingModelCache +from apps.datasource.crud.datasource import updateField +from apps.datasource.crud.table import save_ds_embedding +from apps.datasource.embedding.ds_embedding import get_ds_embedding +from apps.datasource.models.datasource import CoreDatasource, CoreField +from common.core.embedding_config import load_embedding_config +from common.utils import embedding_threads + + +def test_saved_datasource_tail_ranks_allowed_candidates_using_complete_chunks( + environment, monkeypatch +): + from apps.datasource.crud.table import _resource_input + from apps.datasource.embedding.metadata_chunks import read_metadata + + database, _client, jobs = environment + model = BoundaryModel() + monkeypatch.setattr(EmbeddingModelCache, "get_model", lambda: model) + with Session(database) as session: + for key in range(2, 14): + session.add( + CoreDatasource( + id=key, name=f"source_{key}", type="pg", embedding="[1,0]" + ) + ) + for index in range(2, 122): + session.add( + CoreField( + id=index, + ds_id=1, + table_id=1, + field_name=f"field_{index}", + field_type="INT", + field_index=index, + ) + ) + session.commit() + updateField( + session, + CoreField(id=121, ds_id=1, table_id=1, checked=True, custom_comment="TAIL"), + ) + run_jobs(jobs) + save_ds_embedding(embedding_threads.session_maker, list(range(2, 14))) + candidates = [{"id": key, "name": f"source_{key}"} for key in range(12, 0, -1)] + with Session(database) as session: + source = session.get(CoreDatasource, 1) + vectors = read_metadata( + session, "datasource", 1, _resource_input(session, source) + ) + assert len(vectors) > 1 + selected = get_ds_embedding( + session, + candidates, + None, + "tail synonym", + config=replace(load_embedding_config(session), datasource_count=10), + ) + assert len(selected) == 10 + assert selected[0] is candidates[-1] + assert 13 not in {item["id"] for item in selected} + assert all(set(item) == {"id", "name"} for item in selected) + assert "vectors" not in source.model_dump() + + +@pytest.mark.parametrize( + "damage", + [ + "missing", + "count", + "json", + "zero", + "nonfinite", + "dimension", + "version", + "model", + "input", + "checksum", + ], +) +def test_any_invalid_datasource_skips_entire_layer_even_with_valid_legacy_vector( + environment, monkeypatch, damage +): + from apps.datasource.embedding.metadata_chunks import fingerprint + from apps.datasource.models.metadata_embedding import MetadataEmbedding + + database, _client, _jobs = environment + monkeypatch.setattr(EmbeddingModelCache, "get_model", lambda: BoundaryModel()) + with Session(database) as session: + session.add(CoreDatasource(id=2, name="other", type="pg", embedding="[0,1]")) + session.commit() + save_ds_embedding(embedding_threads.session_maker, [1, 2]) + candidates = [{"id": 1, "name": "test"}, {"id": 2, "name": "other"}] + with Session(database) as session: + config = replace(load_embedding_config(session), datasource_count=1) + assert len(get_ds_embedding(session, candidates, None, "q", config=config)) == 1 + record = session.get(MetadataEmbedding, ("datasource", 2)) + if damage == "missing": + session.delete(record) + elif damage == "count": + record.chunk_count += 1 + elif damage in ("json", "zero", "nonfinite", "dimension"): + record.vectors = { + "json": "broken", + "zero": "[[0,0]]", + "nonfinite": "[[NaN,1]]", + "dimension": "[[1,0,0]]", + }[damage] + record.chunk_count = 1 + record.dimension = 3 if damage == "dimension" else 2 + record.vectors_hash = fingerprint(record.vectors) + elif damage == "version": + record.format_version += 1 + elif damage == "model": + record.model_id = "stale-model" + elif damage == "input": + session.get(CoreDatasource, 2).description = "new content" + else: + record.vectors_hash = "bad" + session.commit() + assert ( + get_ds_embedding(session, candidates, None, "q", config=config) + is candidates + ) + + +def test_single_datasource_skips_provider_and_missing_representation( + environment, monkeypatch +): + database, _client, _jobs = environment + monkeypatch.setattr( + EmbeddingModelCache, + "get_model", + lambda: pytest.fail("single datasource must skip vectors"), + ) + candidates = [{"id": 1, "name": "test"}] + with Session(database) as session: + assert get_ds_embedding(session, candidates, None, "q") is candidates diff --git a/backend/tests/test_metadata_datasource_chunks_integration.py b/backend/tests/test_metadata_datasource_chunks_integration.py new file mode 100644 index 000000000..760c930d9 --- /dev/null +++ b/backend/tests/test_metadata_datasource_chunks_integration.py @@ -0,0 +1,249 @@ +# ruff: noqa: F811 +"""Opt-in PostgreSQL datasource lifecycle and persisted preselection acceptance.""" + +from concurrent.futures import ThreadPoolExecutor +from dataclasses import replace +from types import SimpleNamespace + +import pytest +from metadata_test_support import read_datasource_vectors +from sqlalchemy.orm import scoped_session, sessionmaker +from sqlmodel import Session +from test_embedding_parameters_integration import ( # noqa: F401 + knowledge_environment, + pytestmark, +) +from test_metadata_table_chunks import BoundaryModel +from test_table_parameters_integration import table_environment # noqa: F401 + +from apps.ai_model.embedding import EmbeddingModelCache +from apps.datasource.crud import datasource as crud +from apps.datasource.crud.table import save_ds_embedding +from apps.datasource.embedding.ds_embedding import get_ds_embedding +from apps.datasource.models.datasource import ( + ColumnSchema, + CoreDatasource, + CoreField, + CoreTable, +) +from common.core.embedding_config import load_embedding_config +from common.utils import embedding_threads + + +@pytest.fixture +def datasource_environment(table_environment, monkeypatch): + database, client, ds_id = table_environment + sessions = scoped_session(sessionmaker(bind=database, class_=Session)) + monkeypatch.setattr(embedding_threads, "session_maker", sessions) + model = BoundaryModel() + monkeypatch.setattr(EmbeddingModelCache, "get_model", lambda: model) + futures = [] + with ThreadPoolExecutor(max_workers=2) as executor: + + def submit(function, *args): + future = executor.submit(function, *args) + futures.append(future) + return future + + monkeypatch.setattr( + embedding_threads, "executor", SimpleNamespace(submit=submit) + ) + yield database, client, ds_id, sessions, futures, model + sessions.remove() + + +def drain(futures): + for future in futures: + future.result(timeout=30) + futures.clear() + + +def test_saved_late_table_field_controls_persisted_datasource_preselection( + datasource_environment, +): + database, _client, ds_id, sessions, futures, model = datasource_environment + with Session(database) as session: + other_ids = [] + for index in range(12): + source = CoreDatasource(name=f"other{index}", type="pg", embedding="[1,0]") + session.add(source) + session.flush() + other_ids.append(source.id) + for index in range(5): + table = CoreTable(ds_id=ds_id, table_name=f"later_table_{index}") + session.add(table) + session.flush() + for field_index in range(30): + field = CoreField( + ds_id=ds_id, + table_id=table.id, + field_name=f"metric{field_index}", + field_type="INT", + field_index=field_index, + ) + session.add(field) + session.flush() + table_id, field_id = table.id, field.id + session.commit() + crud.updateField( + session, + CoreField( + id=field_id, + ds_id=ds_id, + table_id=table_id, + checked=True, + custom_comment="TAIL", + ), + ) + drain(futures) + save_ds_embedding(sessions, other_ids) + candidates = [{"id": key, "name": "allowed"} for key in other_ids[:-1] + [ds_id]] + with Session(database) as session: + assert len(read_datasource_vectors(session, ds_id)) > 30 + result = get_ds_embedding( + session, + candidates, + None, + "synonym", + config=replace(load_embedding_config(session), datasource_count=10), + ) + assert len(result) == 10 and result[0] is candidates[-1] + assert other_ids[-1] not in {candidate["id"] for candidate in result} + assert all(set(candidate) == {"id", "name"} for candidate in result) + assert "TAIL" in "".join(model.inputs) + + +@pytest.mark.parametrize( + "operation", + [ + "rename", + "table_comment", + "table_checked", + "field_comment", + "field_checked", + "choose", + ], +) +@pytest.mark.parametrize("enabled", [True, False]) +def test_metadata_save_invalidates_and_regenerates_parent_representation( + datasource_environment, monkeypatch, operation, enabled +): + from common.core.config import settings + + database, _client, ds_id, _sessions, futures, model = datasource_environment + monkeypatch.setattr(settings, "TABLE_EMBEDDING_ENABLED", enabled) + with Session(database) as session: + before = read_datasource_vectors(session, ds_id) + assert before == [[1, 0]] + table = ( + session.query(CoreTable) + .filter(CoreTable.ds_id == ds_id, CoreTable.checked.is_(True)) + .first() + ) + field = session.query(CoreField).filter(CoreField.table_id == table.id).first() + if operation == "rename": + crud.update_ds( + session, + lambda value: value, + SimpleNamespace(oid=1), + CoreDatasource(id=ds_id, name="renamed", description="TAIL"), + ) + elif operation.startswith("table"): + crud.updateTable( + session, + CoreTable( + id=table.id, + ds_id=ds_id, + checked=operation != "table_checked", + custom_comment="TAIL", + ), + ) + elif operation.startswith("field"): + crud.updateField( + session, + CoreField( + id=field.id, + ds_id=ds_id, + table_id=table.id, + checked=operation != "field_checked", + custom_comment="TAIL", + ), + ) + else: + monkeypatch.setattr( + crud, + "getFieldsByDs", + lambda *_args: [ColumnSchema("TAIL", "INT", "selected")], + ) + monkeypatch.setattr(crud, "get_tables", lambda *_args: []) + monkeypatch.setattr(crud, "check_status", lambda *_args: True) + crud.chooseTables( + session, + lambda value: value, + ds_id, + [CoreTable(table_name="new_selected")], + ) + drain(futures) + with Session(database) as session: + if not enabled: + assert model.inputs == [] + with pytest.raises(ValueError): + read_datasource_vectors(session, ds_id) + return + after = read_datasource_vectors(session, ds_id) + # The saved input is fully current; a legacy vector was not reused. + assert len(after) > 1 + if operation not in ("table_checked", "field_checked"): + assert [1.0, 0.0] in after + else: + assert [1.0, 0.0] not in after + + +def test_datasource_edit_during_encoding_never_publishes_old_input( + datasource_environment, monkeypatch +): + from threading import Event + + database, _client, ds_id, _sessions, futures, model = datasource_environment + old_started, release_old = Event(), Event() + new_started, release_new = Event(), Event() + encode = model.embed_documents + + def controlled_encode(texts): + if any("OLDER" in text for text in texts): + old_started.set() + assert release_old.wait(10), "old provider was not released" + if any("TAIL" in text for text in texts): + new_started.set() + assert release_new.wait(10), "new provider was not released" + return encode(texts) + + monkeypatch.setattr(model, "embed_documents", controlled_encode) + try: + with Session(database) as session: + crud.update_ds( + session, + lambda value: value, + SimpleNamespace(oid=1), + CoreDatasource(id=ds_id, name="source", description="OLDER"), + ) + assert old_started.wait(10) + with Session(database) as session: + crud.update_ds( + session, + lambda value: value, + SimpleNamespace(oid=1), + CoreDatasource(id=ds_id, name="source", description="TAIL"), + ) + release_old.set() + assert new_started.wait(10) + with Session(database) as session: + with pytest.raises(ValueError): + read_datasource_vectors(session, ds_id) + release_new.set() + drain(futures) + with Session(database) as session: + assert [1.0, 0.0] in read_datasource_vectors(session, ds_id) + finally: + release_old.set() + release_new.set() diff --git a/backend/tests/test_metadata_table_chunks_integration.py b/backend/tests/test_metadata_table_chunks_integration.py index c273f3221..fff66f89a 100644 --- a/backend/tests/test_metadata_table_chunks_integration.py +++ b/backend/tests/test_metadata_table_chunks_integration.py @@ -6,10 +6,11 @@ """ from concurrent.futures import ThreadPoolExecutor +from threading import local from types import SimpleNamespace import pytest -from metadata_test_support import read_table_vectors +from metadata_test_support import read_datasource_vectors, read_table_vectors from sqlalchemy.orm import scoped_session, sessionmaker from sqlmodel import Session from test_embedding_parameters_integration import ( # noqa: F401 @@ -20,9 +21,9 @@ from apps.ai_model.embedding import EmbeddingModelCache from apps.datasource.crud.datasource import updateField -from apps.datasource.crud.table import _table_input +from apps.datasource.crud.table import _resource_input, _table_input from apps.datasource.embedding.table_embedding import calc_table_embedding -from apps.datasource.models.datasource import CoreField, CoreTable +from apps.datasource.models.datasource import CoreDatasource, CoreField, CoreTable from common.core.embedding_config import load_embedding_config from common.utils import embedding_threads @@ -42,10 +43,12 @@ def test_saved_metadata_covers_all_actual_model_inputs( database, _client, ds_id = table_environment sessions = scoped_session(sessionmaker(bind=database, class_=Session)) monkeypatch.setattr(embedding_threads, "session_maker", sessions) - inputs, futures = [], [] + recorded_inputs = {"save_table_embedding": [], "save_ds_embedding": []} + futures = [] + job = local() def embed_documents(texts): - inputs.extend(texts) + recorded_inputs[job.name].extend(texts) return local_model.embed_documents(texts) monkeypatch.setattr( @@ -60,7 +63,11 @@ def embed_documents(texts): with ThreadPoolExecutor(max_workers=2) as executor: def submit(function, *args): - future = executor.submit(function, *args) + def observed_job(): + job.name = function.__name__ + return function(*args) + + future = executor.submit(observed_job) futures.append(future) return future @@ -100,46 +107,60 @@ def submit(function, *args): + ("超长字段注释" * 300 if shape == "long_comment" else ""), ), ) - original = _table_input(session, session.get(CoreTable, table_id)) + originals = { + "save_table_embedding": _table_input( + session, session.get(CoreTable, table_id) + ), + "save_ds_embedding": _resource_input( + session, session.get(CoreDatasource, ds_id) + ), + } for future in futures: future.result(timeout=30) - assert inputs - first = local_model._client._first_module() - first_line = original.splitlines(keepends=True)[0] - # Remove only the permitted repeated table context to reconstruct the body. - reconstructed = inputs[0] + "".join( - chunk[len(first_line) :] if chunk.startswith(first_line) else chunk - for chunk in inputs[1:] - ) - assert reconstructed == original - for chunk in inputs: - prepared = chunk.replace("\n", " ") - actual = local_model._client.tokenize([prepared])["input_ids"][0].tolist() - complete = first.tokenizer(prepared, add_special_tokens=True, truncation=False)[ - "input_ids" - ] - assert actual == complete - assert len(actual) <= first.max_seq_length - if shape != "short": - assert len(inputs) > 1 - assert ( - len( - first.tokenizer(original.replace("\n", " "), truncation=False)[ - "input_ids" - ] - ) - > first.max_seq_length + for job_name, inputs in recorded_inputs.items(): + original = originals[job_name] + assert inputs + first = local_model._client._first_module() + first_line = original.splitlines(keepends=True)[0] + # Remove only the permitted repeated table context to reconstruct the body. + reconstructed = inputs[0] + "".join( + chunk[len(first_line) :] if chunk.startswith(first_line) else chunk + for chunk in inputs[1:] ) - assert ( - len( - local_model._client.tokenize([original.replace("\n", " ")])[ - "input_ids" - ][0] + assert reconstructed == original + for chunk in inputs: + prepared = chunk.replace("\n", " ") + actual = local_model._client.tokenize([prepared])["input_ids"][0].tolist() + complete = first.tokenizer( + prepared, add_special_tokens=True, truncation=False + )["input_ids"] + assert actual == complete + assert len(actual) <= first.max_seq_length + if shape != "short": + assert len(inputs) > 1 + assert ( + len( + first.tokenizer(original.replace("\n", " "), truncation=False)[ + "input_ids" + ] + ) + > first.max_seq_length + ) + assert ( + len( + local_model._client.tokenize([original.replace("\n", " ")])[ + "input_ids" + ][0] + ) + == first.max_seq_length ) - == first.max_seq_length - ) with Session(database) as session: - assert len(read_table_vectors(session, table_id)) == len(inputs) + assert len(read_table_vectors(session, table_id)) == len( + recorded_inputs["save_table_embedding"] + ) + assert len(read_datasource_vectors(session, ds_id)) == len( + recorded_inputs["save_ds_embedding"] + ) selected = calc_table_embedding( [{"id": table_id, "table_name": "业务表", "schema_table": "allowed"}], "TAIL尾部指标", diff --git a/backend/tests/test_table_parameters_integration.py b/backend/tests/test_table_parameters_integration.py index 86d4f7851..c5b458b96 100644 --- a/backend/tests/test_table_parameters_integration.py +++ b/backend/tests/test_table_parameters_integration.py @@ -18,7 +18,7 @@ from apps.ai_model.model_factory import LLMConfig from apps.chat.models.chat_model import Chat, ChatFinishStep, ChatQuestion, ChatRecord from apps.chat.task.llm import LLMService -from apps.datasource.crud.table import _table_input +from apps.datasource.crud.table import _resource_input, _table_input from apps.datasource.embedding.metadata_chunks import fingerprint, publish_metadata from apps.datasource.models.datasource import CoreDatasource, CoreField, CoreTable from apps.datasource.models.metadata_embedding import MetadataEmbedding @@ -86,6 +86,9 @@ def table_environment(knowledge_environment, monkeypatch): # noqa: F811 _table_input(session, table), [json.loads(table.embedding)], ) + publish_metadata( + session, "datasource", ds.id, _resource_input(session, ds), [[1, 0]] + ) session.commit() yield database, client, ds_id sessions.remove() @@ -296,6 +299,15 @@ def add_datasource_candidates(database): embedding="[1,0]", ) ) + session.flush() + for datasource in session.query(CoreDatasource).all(): + publish_metadata( + session, + "datasource", + datasource.id, + _resource_input(session, datasource), + [json.loads(datasource.embedding)], + ) session.commit() @@ -350,8 +362,13 @@ def test_incomplete_datasource_vectors_keep_original_candidate_dtos( .filter(CoreDatasource.name == "second_candidate") .one() ) - ds.embedding = bad_vector - session.add(ds) + record = session.get(MetadataEmbedding, ("datasource", ds.id)) + try: + record.vectors = json.dumps([json.loads(bad_vector)]) + except (TypeError, ValueError): + record.vectors = "broken" + record.vectors_hash = fingerprint(record.vectors) + session.add(record) session.commit() current = task(database, None) current.llm = QuestionProvider(datasource={"id": ds_id, "name": "accessible"}) From 105c3e5f9898c61c0bf2b370524502e13d0e6cc9 Mon Sep 17 00:00:00 2001 From: ulleo Date: Mon, 9 Nov 2026 15:27:58 +0800 Subject: [PATCH 3/4] feat: bound metadata backfill and recover incomplete resources --- backend/apps/datasource/crud/table.py | 45 +- backend/common/utils/embedding_threads.py | 37 +- backend/common/utils/metadata_scheduler.py | 83 +++ backend/tests/test_datasource_lifecycle.py | 11 +- .../test_datasource_lifecycle_integration.py | 480 ++++++++++++++++-- ..._metadata_datasource_chunks_integration.py | 12 +- backend/tests/test_metadata_scheduler.py | 62 +++ .../test_metadata_table_chunks_integration.py | 35 +- .../0001-runtime-embedding-configuration.md | 6 + docs/agents/backend.md | 2 +- 10 files changed, 672 insertions(+), 101 deletions(-) create mode 100644 backend/common/utils/metadata_scheduler.py create mode 100644 backend/tests/test_metadata_scheduler.py diff --git a/backend/apps/datasource/crud/table.py b/backend/apps/datasource/crud/table.py index d9466197f..c1b721011 100644 --- a/backend/apps/datasource/crud/table.py +++ b/backend/apps/datasource/crud/table.py @@ -1,4 +1,4 @@ -from sqlalchemy import select +from sqlalchemy import func, select from apps.ai_model.embedding import EmbeddingModelCache from apps.datasource.embedding.metadata_chunks import ( @@ -83,6 +83,27 @@ def _resource_input(session, record): ) +def _resource_ids(session, resource, ids): + """Keyset pages with a high-water mark; concurrent saves schedule another pass.""" + upper = session.execute(select(func.max(resource.id))).scalar_one() + session.commit() + if upper is None: + return + last = None + while True: + query = select(resource.id).where(resource.id <= upper).order_by(resource.id) + if last is not None: + query = query.where(resource.id > last) + if ids is not None: + query = query.where(resource.id.in_(ids)) + page = list(session.execute(query.limit(32)).scalars()) + session.commit() + if not page: + return + yield from page + last = page[-1] + + def _generate(session_maker, resource, ids=None, config=None): session = session_maker() failed = [] @@ -90,13 +111,9 @@ def _generate(session_maker, resource, ids=None, config=None): config = config or load_embedding_config(session) if not config.table_enabled: return - query = select(resource.id).order_by(resource.id) - if ids is not None: - query = query.where(resource.id.in_(ids)) - pending = list(session.execute(query).scalars()) resource_type = "table" if resource is CoreTable else "datasource" session.commit() - for key in pending: + for key in _resource_ids(session, resource, ids): for attempt in range(3): try: lock_embedding_resource(session, resource.__tablename__, key) @@ -159,9 +176,8 @@ def _generate(session_maker, resource, ids=None, config=None): session_maker.remove() -def run_fill_empty_table_and_ds_embedding(session_maker): - # Each startup/reenable is an independent recoverable scan. Resource locks - # deduplicate work across workers and are released even when a process dies. +def run_metadata_embedding_batch(session_maker, table_ids, datasource_ids, scan=False): + # One snapshot at actual worker start, shared by both kinds of resource. session = session_maker() try: config = load_embedding_config(session) @@ -170,15 +186,22 @@ def run_fill_empty_table_and_ds_embedding(session_maker): if not config.table_enabled: return failures = [] - for resource in (CoreTable, CoreDatasource): + for resource, ids in ((CoreTable, table_ids), (CoreDatasource, datasource_ids)): + if not scan and not ids: + continue try: - _generate(session_maker, resource, config=config) + _generate(session_maker, resource, None if scan else ids, config=config) except EmbeddingGenerationError as exc: failures.extend(exc.ids) if failures: raise EmbeddingGenerationError("datasource_metadata", failures) +def run_fill_empty_table_and_ds_embedding(session_maker): + # Each startup/reenable is recoverable; no durable scan completion marker. + run_metadata_embedding_batch(session_maker, [], [], scan=True) + + def save_table_embedding(session_maker, ids: list[int]): _generate(session_maker, CoreTable, ids) diff --git a/backend/common/utils/embedding_threads.py b/backend/common/utils/embedding_threads.py index b698f67f6..0f6134ed0 100644 --- a/backend/common/utils/embedding_threads.py +++ b/backend/common/utils/embedding_threads.py @@ -1,11 +1,12 @@ from concurrent.futures import ThreadPoolExecutor -from typing import List -from sqlalchemy.orm import sessionmaker, scoped_session +from sqlalchemy.orm import scoped_session, sessionmaker + +from common.core.db import engine +from common.utils.metadata_scheduler import MetadataScheduler executor = ThreadPoolExecutor(max_workers=200) -from common.core.db import engine session_maker = scoped_session(sessionmaker(bind=engine)) @@ -13,36 +14,46 @@ # session = session_maker() -def run_save_terminology_embeddings(ids: List[int]): +def run_save_terminology_embeddings(ids: list[int]): from apps.terminology.curd.terminology import save_embeddings + return executor.submit(save_embeddings, session_maker, ids) def fill_empty_terminology_embeddings(): from apps.terminology.curd.terminology import run_fill_empty_embeddings + return executor.submit(run_fill_empty_embeddings, session_maker) -def run_save_data_training_embeddings(ids: List[int]): +def run_save_data_training_embeddings(ids: list[int]): from apps.data_training.curd.data_training import save_embeddings + return executor.submit(save_embeddings, session_maker, ids) def fill_empty_data_training_embeddings(): from apps.data_training.curd.data_training import run_fill_empty_embeddings + return executor.submit(run_fill_empty_embeddings, session_maker) -def run_save_table_embeddings(ids: List[int]): - from apps.datasource.crud.table import save_table_embedding - return executor.submit(save_table_embedding, session_maker, ids) +def _run_metadata_batch(table_ids, datasource_ids, scan): + from apps.datasource.crud.table import run_metadata_embedding_batch + + return run_metadata_embedding_batch(session_maker, table_ids, datasource_ids, scan) + + +metadata_scheduler = MetadataScheduler(_run_metadata_batch) + + +def run_save_table_embeddings(ids: list[int]): + return metadata_scheduler.submit("table", ids) -def run_save_ds_embeddings(ids: List[int]): - from apps.datasource.crud.table import save_ds_embedding - return executor.submit(save_ds_embedding, session_maker, ids) +def run_save_ds_embeddings(ids: list[int]): + return metadata_scheduler.submit("datasource", ids) def fill_empty_table_and_ds_embeddings(): - from apps.datasource.crud.table import run_fill_empty_table_and_ds_embedding - return executor.submit(run_fill_empty_table_and_ds_embedding, session_maker) + return metadata_scheduler.submit() diff --git a/backend/common/utils/metadata_scheduler.py b/backend/common/utils/metadata_scheduler.py new file mode 100644 index 000000000..8d0906486 --- /dev/null +++ b/backend/common/utils/metadata_scheduler.py @@ -0,0 +1,83 @@ +"""Bounded, coalescing metadata work; persisted validity is the recovery ledger.""" + +from collections.abc import Callable +from concurrent.futures import Future, ThreadPoolExecutor +from threading import Lock + + +class MetadataScheduler: + """One active batch and one pending batch, never one queued job per save. + + Overflow becomes a full paged scan. Requests received during a running scan + remain pending, so an edit to an already scanned resource is not lost. + Futures report completion of their coalesced batch, including its failures. + """ + + def __init__( + self, + generate: Callable[[list[int], list[int], bool], None], + capacity: int = 128, + executor=None, + ): + self._generate = generate + self._capacity = capacity + self._executor = executor or ThreadPoolExecutor( + max_workers=1, thread_name_prefix="metadata-embedding" + ) + self._lock = Lock() + self._pending: Future | None = None + self._ids: dict[str, set[int]] = {"table": set(), "datasource": set()} + self._scan = False + self._running = False + self._closed = False + + def submit(self, resource: str | None = None, ids=()) -> Future: + with self._lock: + if self._closed: + raise RuntimeError("cannot schedule new futures after shutdown") + if resource not in (None, "table", "datasource"): + raise ValueError("Unknown metadata resource") + if self._pending is None: + self._pending = Future() + # A shared completion must not be cancellable by one caller. + self._pending.set_running_or_notify_cancel() + if resource is None: + self._scan = True + elif not self._scan: + for key in ids: + self._ids[resource].add(key) + if sum(map(len, self._ids.values())) > self._capacity: + self._scan = True + break + if self._scan: + for keys in self._ids.values(): + keys.clear() + future = self._pending + if not self._running: + self._running = True + self._executor.submit(self._drain) + return future + + def _drain(self): + while True: + with self._lock: + if self._pending is None: + self._running = False + return + future, self._pending = self._pending, None + tables = sorted(self._ids["table"]) + datasources = sorted(self._ids["datasource"]) + scan, self._scan = self._scan, False + for keys in self._ids.values(): + keys.clear() + try: + self._generate(tables, datasources, scan) + except Exception as exc: + future.set_exception(exc) + else: + future.set_result(None) + + def shutdown(self, wait: bool = True): + with self._lock: + self._closed = True + self._executor.shutdown(wait=wait) diff --git a/backend/tests/test_datasource_lifecycle.py b/backend/tests/test_datasource_lifecycle.py index a88209481..12db8c4b8 100644 --- a/backend/tests/test_datasource_lifecycle.py +++ b/backend/tests/test_datasource_lifecycle.py @@ -22,6 +22,7 @@ from apps.datasource.models.metadata_embedding import MetadataEmbedding from common.core.config import settings from common.utils import embedding_threads +from common.utils.metadata_scheduler import MetadataScheduler @pytest.fixture @@ -40,11 +41,13 @@ def environment(monkeypatch): maker = scoped_session(sessionmaker(bind=database, class_=Session)) jobs = [] monkeypatch.setattr(embedding_threads, "session_maker", maker) - monkeypatch.setattr( - embedding_threads, - "executor", - SimpleNamespace(submit=lambda function, *args: jobs.append((function, args))), + scheduler = MetadataScheduler( + embedding_threads._run_metadata_batch, + executor=SimpleNamespace( + submit=lambda function, *args: jobs.append((function, args)) + ), ) + monkeypatch.setattr(embedding_threads, "metadata_scheduler", scheduler) monkeypatch.setattr(settings, "TABLE_EMBEDDING_ENABLED", True) with TestClient( parameter_app(database, monkeypatch), raise_server_exceptions=False diff --git a/backend/tests/test_datasource_lifecycle_integration.py b/backend/tests/test_datasource_lifecycle_integration.py index 713f8190b..56b5da13a 100644 --- a/backend/tests/test_datasource_lifecycle_integration.py +++ b/backend/tests/test_datasource_lifecycle_integration.py @@ -3,7 +3,11 @@ from concurrent.futures import ThreadPoolExecutor import pytest -from metadata_test_support import metadata_model, read_table_vectors +from metadata_test_support import ( + metadata_model, + read_datasource_vectors, + read_table_vectors, +) from sqlalchemy.orm import scoped_session, sessionmaker from sqlmodel import Session from test_embedding_parameters import save, values @@ -14,6 +18,8 @@ from test_table_parameters_integration import table_environment # noqa: F401 from apps.datasource.embedding.metadata_chunks import invalidate_chunks +from common.utils import embedding_threads +from common.utils.metadata_scheduler import MetadataScheduler @pytest.fixture @@ -24,7 +30,12 @@ def lifecycle_environment(table_environment, monkeypatch): # noqa: F811 monkeypatch.setattr("apps.system.schemas.permission.engine", database) with ThreadPoolExecutor(max_workers=4) as executor: monkeypatch.setattr("common.utils.embedding_threads.executor", executor) - yield database, client, ds_id + scheduler = MetadataScheduler(embedding_threads._run_metadata_batch) + monkeypatch.setattr(embedding_threads, "metadata_scheduler", scheduler) + try: + yield database, client, ds_id + finally: + scheduler.shutdown() sessions.remove() @@ -79,8 +90,6 @@ def test_field_edit_while_disabled_invalidates_table_and_parent( def test_generation_reads_persisted_switch_at_task_start( lifecycle_environment, monkeypatch ): - from types import SimpleNamespace - from sqlalchemy.orm import scoped_session, sessionmaker from sqlmodel import Session @@ -88,6 +97,7 @@ def test_generation_reads_persisted_switch_at_task_start( from apps.datasource.crud.datasource import get_ds from apps.datasource.crud.table import run_fill_empty_table_and_ds_embedding from apps.datasource.models.datasource import CoreDatasource, CoreTable + from apps.datasource.models.metadata_embedding import MetadataEmbedding database, client, ds_id = lifecycle_environment assert ( @@ -98,14 +108,13 @@ def test_generation_reads_persisted_switch_at_task_start( with Session(database) as session: session.query(CoreDatasource).update({"embedding": None}) session.query(CoreTable).update({"embedding": None}) + session.query(MetadataEmbedding).delete() session.commit() inputs = [] monkeypatch.setattr( EmbeddingModelCache, "get_model", - lambda: SimpleNamespace( - embed_query=lambda value: inputs.append(value) or [1, 0] - ), + lambda: metadata_model(embed=lambda value: inputs.append(value) or [1, 0]), ) run_fill_empty_table_and_ds_embedding(sessions) assert inputs == [] @@ -178,43 +187,62 @@ def test_metadata_operations_invalidate_parent_while_disabled( assert get_tables_by_ds_id(session, ds_id) == [] -def test_backfill_repairs_invalid_json_but_keeps_valid_vectors( - lifecycle_environment, monkeypatch +@pytest.mark.parametrize( + "damage", ["missing", "format", "model", "input", "incomplete", "invalid"] +) +def test_backfill_repairs_invalid_chunks_but_keeps_valid_vectors( + lifecycle_environment, monkeypatch, damage ): - from types import SimpleNamespace - from apps.ai_model.embedding import EmbeddingModelCache - from apps.datasource.crud.datasource import get_ds from apps.datasource.crud.table import ( get_tables_by_ds_id, run_fill_empty_table_and_ds_embedding, ) - from apps.datasource.models.datasource import CoreDatasource, CoreTable + from apps.datasource.models.metadata_embedding import MetadataEmbedding database, _client, ds_id = lifecycle_environment sessions = scoped_session(sessionmaker(bind=database, class_=Session)) with Session(database) as session: tables = get_tables_by_ds_id(session, ds_id) ids = [table.id for table in tables] - for table, vector in zip( - tables, ["[]", "not-json", "[0,0]", "[0,1]"], strict=True - ): - table.embedding = vector - session.add(table) - session.get(CoreDatasource, ds_id).embedding = "null" + preserved = read_table_vectors(session, ids[-1]) + # Legacy vectors remain nonempty; only the new storage determines completion. + for key in ids[:-1]: + row = session.get(MetadataEmbedding, ("table", key)) + if damage == "missing": + session.delete(row) + elif damage == "format": + row.format_version = 0 + elif damage == "model": + row.model_id = "outdated-model" + elif damage == "input": + row.input_hash = "outdated-input" + elif damage == "incomplete": + row.chunk_count += 1 + else: + row.vectors = "broken" + invalidate_chunks(session, "datasource", [ds_id]) session.commit() + inputs = [] monkeypatch.setattr( EmbeddingModelCache, "get_model", - lambda: SimpleNamespace(embed_query=lambda _value: [1, 0]), + lambda: metadata_model( + embed=lambda value: inputs.append(value) or [1, 0], limit=10000 + ), ) try: run_fill_empty_table_and_ds_embedding(sessions) with Session(database) as session: - assert [session.get(CoreTable, i).embedding for i in ids] == [ - "[1.0, 0.0]" - ] * 3 + ["[0,1]"] - assert get_ds(session, ds_id).embedding == "[1.0, 0.0]" + assert [read_table_vectors(session, key) for key in ids[:-1]] == [ + [[1, 0]] + ] * 3 + assert read_table_vectors(session, ids[-1]) == preserved + assert read_datasource_vectors(session, ds_id) == [[1, 0]] + assert len(inputs) == 4 + inputs.clear() + run_fill_empty_table_and_ds_embedding(sessions) + assert inputs == [] finally: sessions.remove() @@ -286,10 +314,9 @@ def test_reenable_asynchronously_fills_invalidated_metadata( lifecycle_environment, monkeypatch ): import time - from types import SimpleNamespace from apps.ai_model.embedding import EmbeddingModelCache - from apps.datasource.crud.datasource import get_ds, updateField + from apps.datasource.crud.datasource import updateField from apps.datasource.crud.table import get_tables_by_ds_id from apps.datasource.models.datasource import CoreField @@ -314,7 +341,7 @@ def test_reenable_asynchronously_fills_invalidated_metadata( monkeypatch.setattr( EmbeddingModelCache, "get_model", - lambda: SimpleNamespace(embed_query=lambda _value: [0.6, 0.8]), + lambda: metadata_model([0.6, 0.8]), ) started = time.monotonic() assert ( @@ -324,13 +351,21 @@ def test_reenable_asynchronously_fills_invalidated_metadata( assert time.monotonic() - started < 1 while time.monotonic() - started < 3: with Session(database) as session: - vectors = [t.embedding for t in get_tables_by_ds_id(session, ds_id)] - if get_ds(session, ds_id).embedding == "[0.6, 0.8]" and all(vectors): - break + try: + vectors = [ + read_table_vectors(session, t.id) + for t in get_tables_by_ds_id(session, ds_id) + ] + if all( + v == [0.6, 0.8] for v in read_datasource_vectors(session, ds_id) + ): + break + except ValueError: + pass time.sleep(0.02) else: pytest.fail("enabling did not fill missing metadata vectors") - assert vectors.count("[0.6, 0.8]") == 1 + assert vectors.count([[0.6, 0.8]]) == 1 @pytest.mark.parametrize("resource", ["table", "datasource", "datasource_field"]) @@ -364,7 +399,9 @@ def embed(value): return [0, 1] if "latest content" in value else [1, 0] monkeypatch.setattr( - EmbeddingModelCache, "get_model", lambda: metadata_model(embed=embed) + EmbeddingModelCache, + "get_model", + lambda: metadata_model(embed=embed, limit=10000), ) with Session(database) as session: table = next(t for t in get_tables_by_ds_id(session, ds_id) if t.checked) @@ -376,6 +413,7 @@ def embed(value): invalidate_chunks(session, "table", [table_id]) else: session.get(CoreDatasource, ds_id).embedding = None + invalidate_chunks(session, "datasource", [ds_id]) session.commit() generator = save_table_embedding if resource == "table" else save_ds_embedding with ThreadPoolExecutor(max_workers=1) as workers: @@ -421,15 +459,12 @@ def embed(value): release.set() future.result(timeout=5) with Session(database) as session: - result = ( - next(t for t in get_tables_by_ds_id(session, ds_id) if t.id == table_id) - if resource == "table" - else crud.get_ds(session, ds_id) - ) if resource == "table": assert read_table_vectors(session, table_id) == [[0, 1]] else: - assert result.embedding == "[0.0, 1.0]" + assert all( + vector == [0, 1] for vector in read_datasource_vectors(session, ds_id) + ) if resource == "table": assert crud.get_ds(session, ds_id).embedding is None assert "latest content" in inputs[-1] @@ -439,7 +474,6 @@ def embed(value): def test_failed_generation_leaves_candidates_available( lifecycle_environment, monkeypatch, bad_vector ): - from types import SimpleNamespace from test_table_parameters_integration import configure, run, task @@ -457,11 +491,13 @@ def test_failed_generation_leaves_candidates_available( table = next(t for t in get_tables_by_ds_id(session, ds_id) if t.checked) table.embedding = None session.get(CoreDatasource, ds_id).embedding = None + invalidate_chunks(session, "table", [table.id]) + invalidate_chunks(session, "datasource", [ds_id]) session.commit() monkeypatch.setattr( EmbeddingModelCache, "get_model", - lambda: SimpleNamespace(embed_query=lambda _: bad_vector), + lambda: metadata_model(embed=lambda _: bad_vector), ) sessions = scoped_session(sessionmaker(bind=database, class_=Session)) with pytest.raises(EmbeddingGenerationError): @@ -498,6 +534,8 @@ def test_process_workers_deduplicate_and_recover_after_crash( table = get_tables_by_ds_id(session, ds_id)[0] table.embedding = None session.get(CoreDatasource, ds_id).embedding = None + invalidate_chunks(session, "table", [table.id]) + invalidate_chunks(session, "datasource", [ds_id]) session.commit() with database.connect() as connection: schema = connection.execute(text("select current_schema()")).scalar_one() @@ -510,6 +548,7 @@ def test_process_workers_deduplicate_and_recover_after_crash( from sqlalchemy.orm import scoped_session, sessionmaker from sqlmodel import Session, create_engine from apps.ai_model.embedding import EmbeddingModelCache +from metadata_test_support import metadata_model from common.core.config import settings from common.utils import embedding_threads url, schema, app, directory = sys.argv[1:] @@ -526,8 +565,9 @@ def embed(value): raise TimeoutError('provider barrier') time.sleep(0.01) return [0.6, 0.8] -EmbeddingModelCache.get_model = staticmethod(lambda: SimpleNamespace(embed_query=embed)) +EmbeddingModelCache.get_model = staticmethod(lambda: metadata_model(embed=embed, limit=10000)) embedding_threads.fill_empty_table_and_ds_embeddings().result(timeout=30) +embedding_threads.metadata_scheduler.shutdown(wait=True) embedding_threads.executor.shutdown(wait=True) engine.dispose() print('completed') @@ -540,7 +580,15 @@ def embed(value): application, str(tmp_path), ] - env = {**os.environ, "PYTHONPATH": str(Path(__file__).parents[1].resolve())} + env = { + **os.environ, + "PYTHONPATH": os.pathsep.join( + [ + str(Path(__file__).parents[1].resolve()), + str(Path(__file__).parent.resolve()), + ] + ), + } processes = [] def await_state(predicate): @@ -600,8 +648,10 @@ def waiting(): ] assert len(generated) == (3 if crash_first else 2) with Session(database) as session: - assert session.get(CoreDatasource, ds_id).embedding == "[0.6, 0.8]" - assert get_tables_by_ds_id(session, ds_id)[0].embedding == "[0.6, 0.8]" + assert read_datasource_vectors(session, ds_id) == [[0.6, 0.8]] + assert read_table_vectors( + session, get_tables_by_ds_id(session, ds_id)[0].id + ) == [[0.6, 0.8]] def test_create_and_empty_field_sync_recover_after_enable( @@ -611,6 +661,7 @@ def test_create_and_empty_field_sync_recover_after_enable( import time from types import SimpleNamespace + from apps.ai_model.embedding import EmbeddingModelCache from apps.datasource.crud import datasource as crud from apps.datasource.crud.table import get_tables_by_ds_id from apps.datasource.models.datasource import ( @@ -620,6 +671,9 @@ def test_create_and_empty_field_sync_recover_after_enable( CreateDatasource, ) + monkeypatch.setattr( + EmbeddingModelCache, "get_model", lambda: metadata_model([1, 0]) + ) database, client, _ds_id = lifecycle_environment assert ( save(client, [{"pkey": "embedding.table_enabled", "pval": False}]).status_code @@ -668,11 +722,339 @@ def test_create_and_empty_field_sync_recover_after_enable( deadline = time.monotonic() + 3 while time.monotonic() < deadline: with Session(database) as session: - if ( - crud.get_ds(session, ds_id).embedding - and get_tables_by_ds_id(session, ds_id)[0].embedding - ): - break + try: + if read_datasource_vectors(session, ds_id) and read_table_vectors( + session, table_id + ): + break + except ValueError: + pass time.sleep(0.02) else: pytest.fail("created datasource remained unfilled") + + +def test_backfill_pages_100_tables_and_preserves_valid_resources( + lifecycle_environment, monkeypatch +): + from sqlalchemy import event + + from apps.ai_model.embedding import EmbeddingModelCache + from apps.datasource.crud.table import run_fill_empty_table_and_ds_embedding + from apps.datasource.models.datasource import CoreTable + + database, _client, ds_id = lifecycle_environment + with Session(database) as session: + for index in range(100): + session.add( + CoreTable(ds_id=ds_id, table_name=f"bulk_{index}", embedding="[1,0]") + ) + session.commit() + ids = [row.id for row in session.query(CoreTable).all()] + inputs, scans = [], [] + monkeypatch.setattr( + EmbeddingModelCache, + "get_model", + lambda: metadata_model(embed=lambda value: inputs.append(value) or [1, 0]), + ) + + def observe(_conn, _cursor, statement, _parameters, _context, _many): + if ( + statement.startswith("SELECT core_table.id \nFROM") + and "FOR UPDATE" not in statement + ): + scans.append(statement) + + event.listen(database, "before_cursor_execute", observe) + sessions = scoped_session(sessionmaker(bind=database, class_=Session)) + try: + run_fill_empty_table_and_ds_embedding(sessions) + assert scans and all("LIMIT" in statement for statement in scans) + assert len(scans) >= 4 + with Session(database) as session: + assert all(read_table_vectors(session, key) for key in ids) + assert read_datasource_vectors(session, ds_id) + inputs.clear() + run_fill_empty_table_and_ds_embedding(sessions) + assert inputs == [] + finally: + event.remove(database, "before_cursor_execute", observe) + sessions.remove() + + +def test_bulk_save_100_tables_and_continuous_edits_use_one_model_worker( + lifecycle_environment, monkeypatch, capsys +): + import json + import time + from dataclasses import replace + from threading import Event, Lock + from types import SimpleNamespace + + from apps.ai_model.embedding import EmbeddingModelCache + from apps.datasource.crud import datasource as crud + from apps.datasource.crud.table import get_tables_by_ds_id + from apps.datasource.models.datasource import ColumnSchema, CoreField, CoreTable + from common.core.embedding_config import load_embedding_config + + database, _client, ds_id = lifecycle_environment + entered, release = Event(), Event() + mutex = Lock() + active = peak = calls = 0 + encode_seconds = 0 + + def encode(value): + nonlocal active, peak, calls, encode_seconds + started = time.monotonic() + with mutex: + active += 1 + peak = max(peak, active) + calls += 1 + first = calls == 1 + try: + if first: + entered.set() + assert release.wait(30) + return [1, 0] if "latest_19" in value else [0, 1] + finally: + with mutex: + active -= 1 + encode_seconds += time.monotonic() - started + + model = metadata_model(embed=encode) + model.embed_query = lambda _value: [1, 0] + monkeypatch.setattr(EmbeddingModelCache, "get_model", lambda: model) + monkeypatch.setattr(crud, "get_tables", lambda *_args: []) + monkeypatch.setattr(crud, "check_status", lambda *_args: True) + monkeypatch.setattr( + crud, + "getFieldsByDs", + lambda _session, _ds, name: [ + ColumnSchema(f"field_{index}", "INT", "metric") + for index in range(120 if int(name.split("_")[-1]) < 20 else 8) + ], + ) + started = time.monotonic() + try: + with Session(database) as session: + crud.chooseTables( + session, + lambda value: value, + ds_id, + [ + CoreTable(table_name=f"bulk_{index}", table_comment="metrics") + for index in range(100) + ], + ) + saved_seconds = time.monotonic() - started + assert entered.wait(5) + assert not release.is_set() # Save returned while generation is blocked. + with Session(database) as session: + tables = get_tables_by_ds_id(session, ds_id) + assert len(tables) == 100 + config = replace(load_embedding_config(session), table_count=10) + fallback, names = crud.get_table_schema( + session, + SimpleNamespace(id=1, oid=1), + crud.get_ds(session, ds_id), + "metric question", + config=config, + ) + assert len(names) == 100 + assert all("vectors" not in table.model_dump() for table in tables) + field = ( + session.query(CoreField) + .filter(CoreField.table_id == tables[0].id) + .first() + ) + field_id, table_id = field.id, field.table_id + edit_started = time.monotonic() + for index in range(20): + with Session(database) as session: + crud.updateField( + session, + CoreField( + id=field_id, + ds_id=ds_id, + table_id=table_id, + checked=True, + custom_comment=f"latest_{index}", + ), + ) + edit_seconds = time.monotonic() - edit_started + pending = embedding_threads.fill_empty_table_and_ds_embeddings() + finally: + release.set() + pending.result(timeout=30) + with Session(database) as session: + table_chunks = sum( + len(read_table_vectors(session, table.id)) for table in tables + ) + datasource_chunks = len(read_datasource_vectors(session, ds_id)) + assert [1, 0] in read_table_vectors(session, table_id) + selected, names = crud.get_table_schema( + session, + SimpleNamespace(id=1, oid=1), + crud.get_ds(session, ds_id), + "metric question", + config=config, + ) + assert len(names) == 10 + assert peak == 1 + # Captured on demand with -s; no business metadata or credentials are printed. + with capsys.disabled(): + print( + "BULK_METRICS:" + + json.dumps( + { + "tables": 100, + "fields": 3040, + "save_seconds": saved_seconds, + "20_edits_seconds": edit_seconds, + "total_seconds": time.monotonic() - started, + "encode_calls": calls, + "encode_seconds_including_barrier": encode_seconds, + "max_concurrent_model_calls": peak, + "table_chunks": table_chunks, + "datasource_chunks": datasource_chunks, + "fallback_tables": 100, + "fallback_context_chars": len(fallback), + "complete_context_chars": len(selected), + "complete_tables": len(names), + } + ) + ) + + +def test_backfill_failure_keeps_other_progress_and_later_scan_recovers( + lifecycle_environment, monkeypatch +): + from apps.ai_model.embedding import EmbeddingModelCache + from apps.datasource.crud.table import ( + get_tables_by_ds_id, + run_fill_empty_table_and_ds_embedding, + ) + from common.utils.embedding_lifecycle import EmbeddingGenerationError + + database, _client, ds_id = lifecycle_environment + with Session(database) as session: + tables = get_tables_by_ds_id(session, ds_id) + ids = [table.id for table in tables] + broken_name = tables[0].table_name + invalidate_chunks(session, "table", ids) + session.commit() + attempts = [] + + def embed(value): + attempts.append(value) + if value.startswith(f"# Table: {broken_name}"): + raise RuntimeError("one resource failed") + return [1, 0] + + monkeypatch.setattr( + EmbeddingModelCache, "get_model", lambda: metadata_model(embed=embed) + ) + sessions = scoped_session(sessionmaker(bind=database, class_=Session)) + with pytest.raises(EmbeddingGenerationError) as failure: + run_fill_empty_table_and_ds_embedding(sessions) + assert failure.value.ids == (ids[0],) + assert sum(value.startswith(f"# Table: {broken_name}") for value in attempts) == 3 + with Session(database) as session: + with pytest.raises(ValueError): + read_table_vectors(session, ids[0]) + assert all(read_table_vectors(session, key) for key in ids[1:]) + recovered = [] + monkeypatch.setattr( + EmbeddingModelCache, + "get_model", + lambda: metadata_model(embed=lambda value: recovered.append(value) or [1, 0]), + ) + run_fill_empty_table_and_ds_embedding(sessions) + assert len(recovered) == 1 + with Session(database) as session: + assert all(read_table_vectors(session, key) for key in ids) + + +def test_deleting_tables_during_encoding_does_not_restore_their_chunks( + lifecycle_environment, monkeypatch +): + from threading import Event + + from apps.ai_model.embedding import EmbeddingModelCache + from apps.datasource.crud import datasource as crud + from apps.datasource.crud.table import get_tables_by_ds_id + from apps.datasource.embedding.metadata_chunks import read_metadata + + database, _client, ds_id = lifecycle_environment + entered, release = Event(), Event() + with Session(database) as session: + table_id = get_tables_by_ds_id(session, ds_id)[0].id + invalidate_chunks(session, "table", [table_id]) + session.commit() + + def embed(_value): + entered.set() + assert release.wait(5) + return [1, 0] + + monkeypatch.setattr( + EmbeddingModelCache, "get_model", lambda: metadata_model(embed=embed) + ) + monkeypatch.setattr(crud, "check_status", lambda *_args: True) + monkeypatch.setattr(crud, "get_tables", lambda *_args: []) + first = embedding_threads.run_save_table_embeddings([table_id]) + try: + assert entered.wait(5) + with Session(database) as session: + crud.chooseTables(session, lambda value: value, ds_id, []) + later = embedding_threads.fill_empty_table_and_ds_embeddings() + finally: + release.set() + first.result(timeout=5) + later.result(timeout=5) + with Session(database) as session: + assert get_tables_by_ds_id(session, ds_id) == [] + with pytest.raises(ValueError): + read_metadata(session, "table", table_id, "deleted table") + assert read_datasource_vectors(session, ds_id) + + +def test_started_scan_keeps_one_config_snapshot_for_tables_and_datasources( + lifecycle_environment, monkeypatch +): + from threading import Event + + from apps.ai_model.embedding import EmbeddingModelCache + from apps.datasource.crud.table import get_tables_by_ds_id + + database, client, ds_id = lifecycle_environment + with Session(database) as session: + ids = [table.id for table in get_tables_by_ds_id(session, ds_id)] + invalidate_chunks(session, "table", ids) + invalidate_chunks(session, "datasource", [ds_id]) + session.commit() + entered, release = Event(), Event() + + def encode(_value): + entered.set() + assert release.wait(5) + return [1, 0] + + monkeypatch.setattr( + EmbeddingModelCache, "get_model", lambda: metadata_model(embed=encode) + ) + future = embedding_threads.fill_empty_table_and_ds_embeddings() + try: + assert entered.wait(5) + assert ( + save( + client, [{"pkey": "embedding.table_enabled", "pval": False}] + ).status_code + == 200 + ) + finally: + release.set() + future.result(timeout=5) + with Session(database) as session: + assert all(read_table_vectors(session, key) for key in ids) + assert read_datasource_vectors(session, ds_id) diff --git a/backend/tests/test_metadata_datasource_chunks_integration.py b/backend/tests/test_metadata_datasource_chunks_integration.py index 760c930d9..d482c2045 100644 --- a/backend/tests/test_metadata_datasource_chunks_integration.py +++ b/backend/tests/test_metadata_datasource_chunks_integration.py @@ -28,6 +28,7 @@ ) from common.core.embedding_config import load_embedding_config from common.utils import embedding_threads +from common.utils.metadata_scheduler import MetadataScheduler @pytest.fixture @@ -45,10 +46,15 @@ def submit(function, *args): futures.append(future) return future - monkeypatch.setattr( - embedding_threads, "executor", SimpleNamespace(submit=submit) + scheduler = MetadataScheduler( + embedding_threads._run_metadata_batch, + executor=SimpleNamespace(submit=submit, shutdown=executor.shutdown), ) - yield database, client, ds_id, sessions, futures, model + monkeypatch.setattr(embedding_threads, "metadata_scheduler", scheduler) + try: + yield database, client, ds_id, sessions, futures, model + finally: + scheduler.shutdown() sessions.remove() diff --git a/backend/tests/test_metadata_scheduler.py b/backend/tests/test_metadata_scheduler.py new file mode 100644 index 000000000..7f6ea6c4f --- /dev/null +++ b/backend/tests/test_metadata_scheduler.py @@ -0,0 +1,62 @@ +"""The metadata scheduling seam bounds backlog without blocking save callers.""" + +from threading import Event + +from common.utils.metadata_scheduler import MetadataScheduler + + +def test_save_burst_coalesces_to_recovery_scan_without_blocking(): + entered, release = Event(), Event() + completed = [] + + def generate(tables, datasources, scan): + if not completed: + entered.set() + assert release.wait(5) + completed.append((tables, datasources, scan)) + + scheduler = MetadataScheduler(generate, capacity=4) + try: + active = scheduler.submit("table", [1]) + assert entered.wait(5) + pending = scheduler.submit("table", [2]) + for index in range(3, 1003): + assert scheduler.submit("table", [index]) is pending + assert not pending.done() + release.set() + active.result(5) + pending.result(5) + assert completed == [([1], [], False), ([], [], True)] + finally: + release.set() + scheduler.shutdown() + + +def test_failed_batch_reports_error_and_later_edits_still_run(): + import pytest + + entered, release = Event(), Event() + calls = [] + + def generate(tables, _datasources, _scan): + calls.append(tables) + if len(calls) == 1: + entered.set() + assert release.wait(5) + raise ValueError("provider failed") + + scheduler = MetadataScheduler(generate) + try: + first = scheduler.submit("table", [1]) + assert entered.wait(5) + later = scheduler.submit("table", [1]) + release.set() + with pytest.raises(ValueError, match="provider failed"): + first.result(5) + later.result(5) + assert calls == [[1], [1]] + finally: + release.set() + scheduler.shutdown() + with pytest.raises(RuntimeError, match="shutdown"): + scheduler.submit() diff --git a/backend/tests/test_metadata_table_chunks_integration.py b/backend/tests/test_metadata_table_chunks_integration.py index fff66f89a..b50dfb743 100644 --- a/backend/tests/test_metadata_table_chunks_integration.py +++ b/backend/tests/test_metadata_table_chunks_integration.py @@ -6,7 +6,6 @@ """ from concurrent.futures import ThreadPoolExecutor -from threading import local from types import SimpleNamespace import pytest @@ -26,6 +25,7 @@ from apps.datasource.models.datasource import CoreDatasource, CoreField, CoreTable from common.core.embedding_config import load_embedding_config from common.utils import embedding_threads +from common.utils.metadata_scheduler import MetadataScheduler @pytest.fixture(scope="module") @@ -43,12 +43,10 @@ def test_saved_metadata_covers_all_actual_model_inputs( database, _client, ds_id = table_environment sessions = scoped_session(sessionmaker(bind=database, class_=Session)) monkeypatch.setattr(embedding_threads, "session_maker", sessions) - recorded_inputs = {"save_table_embedding": [], "save_ds_embedding": []} - futures = [] - job = local() + all_inputs = [] def embed_documents(texts): - recorded_inputs[job.name].extend(texts) + all_inputs.extend(texts) return local_model.embed_documents(texts) monkeypatch.setattr( @@ -60,20 +58,11 @@ def embed_documents(texts): embed_query=local_model.embed_query, ), ) - with ThreadPoolExecutor(max_workers=2) as executor: - - def submit(function, *args): - def observed_job(): - job.name = function.__name__ - return function(*args) - - future = executor.submit(observed_job) - futures.append(future) - return future - - monkeypatch.setattr( - embedding_threads, "executor", SimpleNamespace(submit=submit) + with ThreadPoolExecutor(max_workers=1) as executor: + scheduler = MetadataScheduler( + embedding_threads._run_metadata_batch, executor=executor ) + monkeypatch.setattr(embedding_threads, "metadata_scheduler", scheduler) with Session(database) as session: table = session.query(CoreTable).filter(CoreTable.ds_id == ds_id).first() table_id = table.id @@ -115,8 +104,14 @@ def observed_job(): session, session.get(CoreDatasource, ds_id) ), } - for future in futures: - future.result(timeout=30) + embedding_threads.fill_empty_table_and_ds_embeddings().result(timeout=30) + scheduler.shutdown() + with Session(database) as session: + table_chunk_count = len(read_table_vectors(session, table_id)) + recorded_inputs = { + "save_table_embedding": all_inputs[:table_chunk_count], + "save_ds_embedding": all_inputs[table_chunk_count:], + } for job_name, inputs in recorded_inputs.items(): original = originals[job_name] assert inputs diff --git a/docs/adr/0001-runtime-embedding-configuration.md b/docs/adr/0001-runtime-embedding-configuration.md index f8e75dfc0..645504df5 100644 --- a/docs/adr/0001-runtime-embedding-configuration.md +++ b/docs/adr/0001-runtime-embedding-configuration.md @@ -13,3 +13,9 @@ 保留现有开关关系和召回语义。新的页面保存严格校验相似度和权重为 `[0,1]` 内有限数值、数量为正整数,非法输入整次拒绝保存;不顺带改变既有启动配置解析行为。 本决策已由 `common/core/embedding_config.py` 的统一类型与直接持久化读取、`LLMService` 任务快照,以及 `embedding_lifecycle.py` / 数据源任务的资源锁和条件写回实现。保存使用参数写入事务锁,后台任务在工作线程开始时读取有效配置;不依赖 xpack 的进程内参数缓存传播。实现状态不等同于所有部署环境均已验收;完整参数、调用链、可重复验证与剩余范围见[设计与影响范围](../design/embedding-parameter-configuration.md)。 + +表与数据源采用完整块集合后,完成标记是 `metadata_embedding` 中与当前输入、部署模型和格式版本一致且完整的表示,旧 `embedding` 字段不参与完成判断。迁移只准备结构;`main.lifespan` 在迁移成功后提交后台扫描,启动无需等待模型编码。启动、重新开启和资源保存统一进入 `common/utils/metadata_scheduler.py`:每个进程一个元数据工作线程,一个执行批次与一个合并的待执行批次;待处理资源 ID 超过容量时转为完整扫描。扫描按 ID 游标分页,以启动扫描时最大 ID 为上界;扫描期间的新保存仍排入下一批。配置在每批实际开始时读取,同批表与数据源共享快照。知识任务继续使用原有调度路径。 + +该调度以吞吐量换取可控的模型并发与积压内存,不持久化“扫描完成”状态。跨进程仍靠资源事务锁串行;输入变动、失败或中断后通过当前块集合的有效性决定重试,已完成且仍有效的资源不会重新编码。每资源有限重试失败后保留未完成状态并报告;其余资源继续处理,后续资源任务、重新开启或重启可恢复。补齐期间继续沿用上述合法候选回退语义,接受完整候选上下文带来的临时开销。 + +升级部署顺序:先停止所有旧版本服务及后台写者,再启动新版本,让正常启动迁移准备结构并提交后台补齐。旧版本写者不维护新块集合的失效契约;本实现没有验证或承诺新旧版本滚动混跑。多进程恢复测试仅覆盖同一新版本。合成模型、合成元数据与真实数据库回归不能替代客户数据、真实关键词提取和完整 SQL 问数验收。 diff --git a/docs/agents/backend.md b/docs/agents/backend.md index c667ac336..a8d6ffd2c 100644 --- a/docs/agents/backend.md +++ b/docs/agents/backend.md @@ -55,7 +55,7 @@ Endpoint 命名沿既有风格: - 事务提交通常发生在 CRUD/service 边界;API handler 不要随意中途 commit。 - embedding、缓存清理或后台任务沿用当前领域的线程任务模式,不在请求路径中阻塞等待长任务。 - 知识向量任务通过 `common/utils/embedding_lifecycle.py` 在实际工作线程开始时读取持久化配置;术语主词/同义词与 SQL 示例问题变化必须在业务事务内使受影响向量失效。生成任务使用按资源的 PostgreSQL 事务 advisory lock、锁后重读和输入条件写回,不能用进程内锁或无条件写回替代。失败向量保持空值,有限重试失败后报告异常,后续资源任务、重新开启和进程启动均可重试。 -- 表与数据源向量任务入口在 `apps/datasource/crud/table.py`,复用上述资源锁并兼容 JSON 向量。元数据写入先按父数据源、子表顺序在同一事务内使向量失效(`embedding_state.py`);生成期间不持有业务行锁,发布前按相同顺序锁行、重读并比较完整输入,防止旧结果覆盖修改。启动与重新开启扫描修复缺失或无效向量,保留有效向量;启动补齐不使用进程生命周期级单次锁。 表的完整分块表示保存在独立 `metadata_embedding` 内部表(`apps/datasource/embedding/metadata_chunks.py`),包含模型、格式版本、输入指纹及完整性信息,不进入管理 DTO。表读取依据当前持久化元数据校验完整集合后取最大块分数;旧单向量不作为新格式完成标记。长度检查使用独立 tokenizer 副本,避免修改共享推理 tokenizer 的截断状态。 +- 表与数据源向量任务入口在 `apps/datasource/crud/table.py`,复用上述资源锁并兼容 JSON 向量。元数据写入先按父数据源、子表顺序在同一事务内使向量失效(`embedding_state.py`);生成期间不持有业务行锁,发布前按相同顺序锁行、重读并比较完整输入,防止旧结果覆盖修改。启动与重新开启扫描修复缺失或无效向量,保留有效向量;启动补齐不使用进程生命周期级单次锁。 表的完整分块表示保存在独立 `metadata_embedding` 内部表(`apps/datasource/embedding/metadata_chunks.py`),包含模型、格式版本、输入指纹及完整性信息,不进入管理 DTO。表读取依据当前持久化元数据校验完整集合后取最大块分数;旧单向量不作为新格式完成标记。长度检查使用独立 tokenizer 副本,避免修改共享推理 tokenizer 的截断状态。 元数据调度在 `common/utils/metadata_scheduler.py`,资源保存、启动和重新开启共用有界合并队列;扫描按 ID 分页,任务开始时读取一次配置快照。排队时不读取开关,失败不记录持久化完成标记。部署升级顺序与恢复约束见 [ADR](../adr/0001-runtime-embedding-configuration.md)。 ## 异步与阻塞 From 991c6872a93237ce80dc880c6796c24b209a90df Mon Sep 17 00:00:00 2001 From: ulleo Date: Mon, 9 Nov 2026 16:46:09 +0800 Subject: [PATCH 4/4] test: evaluate cross-chunk metadata conjunction recall --- .../test_metadata_conjunction_evaluation.py | 429 ++++++++++++++++++ 1 file changed, 429 insertions(+) create mode 100644 backend/tests/test_metadata_conjunction_evaluation.py diff --git a/backend/tests/test_metadata_conjunction_evaluation.py b/backend/tests/test_metadata_conjunction_evaluation.py new file mode 100644 index 000000000..560876e55 --- /dev/null +++ b/backend/tests/test_metadata_conjunction_evaluation.py @@ -0,0 +1,429 @@ +"""Opt-in real-model diagnostic: can the only A+B candidate survive top-10? + +Run explicitly with SQLBOT_RUN_METADATA_CONJUNCTION=1 and +SQLBOT_TEST_DATABASE_URL pointing at an authorized disposable PostgreSQL DB. +Optionally set SQLBOT_METADATA_CONJUNCTION_REPORT to an external JSON file. +This deliberately asserts retrieval quality, so failures are findings, not +infrastructure failures or claims that all customer questions must succeed. +Synthetic keywords are supplied; no LLM, HTTP or customer-data acceptance. +""" + +import hashlib +import importlib.metadata +import json +import os +import random +import subprocess +import time +import uuid +from pathlib import Path + +import pytest + +pytestmark = pytest.mark.skipif( + os.environ.get("SQLBOT_RUN_METADATA_CONJUNCTION") != "1", + reason="explicit disposable PostgreSQL/local-model quality evaluation required", +) + +CASES = { + "region_recovery": ( + "业务大区", + "质保追偿金额", + "按业务大区统计质保追偿金额", + "按地区汇总向供应商追回的质量损失款", + "地区,质量损失款", + ), + "contract_receipts": ( + "合同签订金额", + "回款到账金额", + "对比合同签订金额与回款到账金额", + "签下的合同金额和实际收到的款项分别有多少", + "合同金额,实收款项", + ), + "refund_ratio": ( + "售后退款金额", + "订单实收金额", + "计算售后退款金额占订单实收金额的比例", + "退给客户的钱占实际收到订单款项的比例", + "退款,实收", + ), + "credit_overdue": ( + "客户信用等级", + "逾期应收金额", + "按客户信用等级统计逾期应收金额", + "按客户信用评级汇总过期未收回的欠款", + "信用评级,欠款", + ), +} +LAYOUTS = ("wide_adjacent", "wide_split", "short_decoys_split") +MODES = ("table_hybrid", "table_vector", "datasource_vector") + + +@pytest.fixture(scope="module") +def conjunction_results(tmp_path_factory): + # Import through normal application bootstrap, never AST-load the scorer. + with pytest.MonkeyPatch.context() as patch: + patch.setenv("HF_HUB_OFFLINE", "1") + patch.setenv("TRANSFORMERS_OFFLINE", "1") + import torch + from sqlalchemy import text + from sqlalchemy.orm import scoped_session, sessionmaker + from sqlmodel import Session, create_engine + + import main # noqa: F401 + from apps.ai_model.embedding import EmbeddingModelCache + from apps.datasource.crud.embedding_state import invalidate_metadata + from apps.datasource.crud.table import ( + _resource_input, + _table_input, + save_ds_embedding, + save_table_embedding, + ) + from apps.datasource.embedding.ds_embedding import get_ds_embedding + from apps.datasource.embedding.metadata_chunks import chunk_text, read_metadata + from apps.datasource.embedding.table_embedding import calc_table_embedding + from apps.datasource.models.datasource import ( + CoreDatasource, + CoreField, + CoreTable, + ) + from apps.datasource.models.metadata_embedding import MetadataEmbedding + from common.core.config import settings + from common.core.embedding_config import EmbeddingConfig + + torch.set_num_threads(4) + patch.setattr(settings, "TABLE_EMBEDDING_ENABLED", True) + config = EmbeddingConfig(True, 0.4, 5, 0.4, 5, True, 10, 0.4, True, 10) + real = EmbeddingModelCache.get_model() + transformer = real._client._first_module() + observed = {"blocks": 0, "max_tokens": 0} + queries = {} + + class ObservedModel: + _client = real._client + + def embed_documents(self, values): + prepared = [value.replace("\n", " ").strip() for value in values] + if transformer.do_lower_case: + prepared = [value.lower() for value in prepared] + lengths = [ + len( + transformer.tokenizer( + value, + truncation=False, + verbose=False, + add_special_tokens=True, + )["input_ids"] + ) + for value in prepared + ] + actual = ( + real._client.tokenize(prepared)["attention_mask"] + .sum(dim=1) + .tolist() + ) + assert lengths == actual and max(actual) <= transformer.max_seq_length + observed["blocks"] += len(values) + observed["max_tokens"] = max(observed["max_tokens"], max(actual)) + return real.embed_documents(values) + + def embed_query(self, value): + if value not in queries: + queries[value] = real.embed_query(value) + return queries[value] + + provider = ObservedModel() + patch.setattr(EmbeddingModelCache, "get_model", lambda: provider) + url = os.environ["SQLBOT_TEST_DATABASE_URL"] + assert url.startswith("postgresql+psycopg://") + admin = create_engine(url) + schema = "metadata_conjunction_" + uuid.uuid4().hex + with admin.begin() as connection: + connection.execute(text(f'CREATE SCHEMA "{schema}"')) + database = create_engine( + url, connect_args={"options": f"-csearch_path={schema},public"} + ) + sessions = scoped_session(sessionmaker(bind=database, class_=Session)) + report = { + "revision": subprocess.check_output( + ["git", "rev-parse", "HEAD"], text=True + ).strip(), + "test_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + "versions": { + name: importlib.metadata.version(name) + for name in ( + "sentence-transformers", + "transformers", + "torch", + "sqlbot-xpack", + ) + }, + "candidate_count": 25, + "top_count": 10, + "alpha": 0.4, + "negative_candidates": {"a_only": 11, "b_only": 11, "neither": 2}, + "cases": CASES, + "rows": [], + "coverage": [], + "observed": observed, + } + started = time.perf_counter() + try: + for model in (CoreDatasource, CoreTable, CoreField, MetadataEmbedding): + model.__table__.create(database) + with database.begin() as connection: + connection.execute( + text( + "CREATE TABLE sys_arg (id BIGINT PRIMARY KEY, pkey VARCHAR(255), pval VARCHAR(255), ptype VARCHAR(255), sort_no INTEGER NOT NULL DEFAULT 0)" + ) + ) + + def add_table(session, ds_id, index, a, b, *, auxiliary=False): + table = CoreTable( + ds_id=ds_id, + table_name=f"{'aux' if auxiliary else 'detail'}_{index:03}", + table_comment="经营统计明细", + checked=True, + ) + session.add(table) + session.flush() + for position in range(8 if auxiliary else 120): + label = f"经营辅助指标{position:03}" + if ( + not auxiliary + and position == 1 + and (index == 0 or 1 <= index <= 11) + ): + label = a + if ( + not auxiliary + and position == 2 + and (index == 0 or 12 <= index <= 22) + ): + label = b + session.add( + CoreField( + ds_id=ds_id, + table_id=table.id, + field_name=f"metric_{position:03}", + field_index=position, + field_type="DECIMAL", + field_comment=label, + checked=True, + ) + ) + return table.id + + for case_number, ( + case, + (a, b, exact, paraphrase, paraphrase_keywords), + ) in enumerate(CASES.items()): + with Session(database) as session: + pool = CoreDatasource( + name="表候选集合", description="经营分析", type="pg", oid=1 + ) + session.add(pool) + session.flush() + table_ids, source_table_ids, ds_ids = [], [], [] + for index in range(25): + source = CoreDatasource( + name=f"业务资料_{index:03}", + description="经营分析", + type="pg", + oid=1, + ) + session.add(source) + session.flush() + ds_ids.append(source.id) + table_ids.append(add_table(session, pool.id, index, a, b)) + source_table_ids.append( + add_table(session, source.id, index, a, b) + ) + add_table(session, source.id, index, a, b, auxiliary=True) + session.commit() + for layout in LAYOUTS: + if layout != "wide_adjacent": + changed = ( + [table_ids[0], source_table_ids[0]] + if layout == "wide_split" + else table_ids[1:] + source_table_ids[1:] + ) + with Session(database) as session: + for key in changed: + table = session.get(CoreTable, key) + invalidate_metadata(session, table.ds_id, [key]) + fields = ( + session.query(CoreField) + .filter(CoreField.table_id == key) + .all() + ) + for field in fields: + if layout == "wide_split": + if field.field_index == 2: + field.field_index = 119 + elif field.field_index == 119: + field.field_index = 2 + elif field.field_index >= 3: + field.checked = False + session.add(field) + session.commit() + save_table_embedding(sessions, table_ids) + save_ds_embedding(sessions, ds_ids) + with Session(database) as session: + tables = [] + for key in table_ids: + table = session.get(CoreTable, key) + fields = ( + session.query(CoreField) + .filter( + CoreField.table_id == key, + CoreField.checked.is_(True), + ) + .all() + ) + tables.append( + { + "id": key, + "table_name": table.table_name, + "table_comment": table.table_comment, + "schema_table": _table_input(session, table), + "fields": [ + { + "field_name": f.field_name, + "field_comment": f.field_comment, + "custom_comment": f.custom_comment, + } + for f in fields + ], + } + ) + sources = [ + { + "id": key, + "name": session.get(CoreDatasource, key).name, + "description": "经营分析", + } + for key in ds_ids + ] + random.Random(17 + case_number).shuffle(tables) + random.Random(17 + case_number).shuffle(sources) + for kind, keys, cls in ( + ("table", table_ids, CoreTable), + ("datasource", ds_ids, CoreDatasource), + ): + counts = [] + for key in keys: + content = _resource_input( + session, session.get(cls, key) + ) + counts.append( + len(read_metadata(session, kind, key, content)) + ) + target_input = _resource_input( + session, session.get(cls, keys[0]) + ) + chunks = chunk_text(target_input, provider) + a_chunks = [ + i for i, value in enumerate(chunks) if a in value + ] + b_chunks = [ + i for i, value in enumerate(chunks) if b in value + ] + assert a_chunks and b_chunks + assert bool(set(a_chunks) & set(b_chunks)) == ( + layout == "wide_adjacent" + ) + report["coverage"].append( + { + "case": case, + "layout": layout, + "resource": kind, + "target_chunks": counts[0], + "decoy_min_chunks": min(counts[1:]), + "decoy_max_chunks": max(counts[1:]), + "a_chunks": a_chunks, + "b_chunks": b_chunks, + } + ) + for style, question, keywords in ( + ("exact", exact, f"{a},{b}"), + ("paraphrase", paraphrase, paraphrase_keywords), + ): + for mode in MODES: + if mode == "datasource_vector": + chosen = get_ds_embedding( + session, sources, None, question, config=config + ) + target = ds_ids[0] + else: + chosen = calc_table_embedding( + tables, + question, + session=session, + keywords=keywords + if mode == "table_hybrid" + else None, + config=config, + ) + target = table_ids[0] + selected = [item["id"] for item in chosen] + assert len(selected) == 10, ( + "Fallback/invalid setup must not look like a quality pass" + ) + report["rows"].append( + { + "case": case, + "layout": layout, + "style": style, + "mode": mode, + "question": question, + "keywords": keywords, + "target_hit": target in selected, + "target_rank": selected.index(target) + 1 + if target in selected + else None, + "selected_indices": [ + ( + ds_ids + if mode == "datasource_vector" + else table_ids + ).index(key) + for key in selected + ], + } + ) + print(f"evaluated {case} {layout}", flush=True) + finally: + report["elapsed_seconds"] = time.perf_counter() - started + sessions.remove() + database.dispose() + with admin.begin() as connection: + connection.execute(text(f'DROP SCHEMA "{schema}" CASCADE')) + admin.dispose() + destination = Path( + os.environ.get( + "SQLBOT_METADATA_CONJUNCTION_REPORT", + str(tmp_path_factory.mktemp("conjunction") / "report.json"), + ) + ) + destination.write_text( + json.dumps(report, ensure_ascii=False, indent=2) + "\n" + ) + print(f"conjunction report: {destination}", flush=True) + return report["rows"] + + +@pytest.mark.parametrize("case", CASES) +@pytest.mark.parametrize("layout", LAYOUTS) +@pytest.mark.parametrize("style", ("exact", "paraphrase")) +@pytest.mark.parametrize("mode", MODES) +def test_joint_requirement_keeps_the_only_complete_candidate( + conjunction_results, case, layout, style, mode +): + row = next( + row + for row in conjunction_results + if (row["case"], row["layout"], row["style"], row["mode"]) + == (case, layout, style, mode) + ) + assert row["target_hit"], json.dumps(row, ensure_ascii=False)