embedstamp 0.1.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,99 @@
1
+ {
2
+ "app.description": "Stamp a vector index with its embedding model's fingerprint, check it before querying, and re-embed safely.",
3
+ "app.epilog": "Exit codes for check: 0 same, 10 drift, 11 different, 12 no fingerprint. migrate: 13 switch refused. Other failures: 1 error, 2 usage, 4 save failed.",
4
+ "cmd.demo": "Run the offline practice demo (mock embedders, no network).",
5
+ "cmd.stamp": "Record the fingerprint of an embedder in a store.",
6
+ "cmd.check": "Compare an embedder with the stored fingerprint.",
7
+ "cmd.show": "Show the stored fingerprint.",
8
+ "cmd.migrate": "Re-embed an index into a green collection, report quality, optionally switch.",
9
+ "opt.lang": "Output language: en or ko (default: EMBEDSTAMP_LANG, then LC_ALL, LC_MESSAGES, LANG).",
10
+ "opt.store": "Store spec: local://<dir>, sidecar://<file> or chroma://<db_dir>/<collection>.",
11
+ "opt.embedder": "Embedder spec: fake:<name>[?noise=..&scale=..&prefix=..&dim=..] or fastembed:<model>.",
12
+ "opt.model": "Model name to record (default: taken from the embedder spec).",
13
+ "opt.doc_prefix": "Prefix added to documents (and probe sentences).",
14
+ "opt.query_prefix": "Prefix added to queries.",
15
+ "opt.compact": "Store only a 32-dimensional summary (small, less precise).",
16
+ "opt.json": "Print machine-readable JSON.",
17
+ "opt.to": "Embedder spec of the new model.",
18
+ "opt.from": "Embedder spec of the old model (enables the top-k overlap measurement).",
19
+ "opt.queries": "Text file with one query per line for the overlap measurement.",
20
+ "opt.k": "Top-k used for self-recall and overlap (default 10).",
21
+ "opt.switch": "Switch names after migrating (otherwise the old index stays live).",
22
+ "opt.batch_size": "Documents embedded per batch (default 64).",
23
+ "opt.min_self_recall": "Refuse to switch below this self-recall (default 0.9).",
24
+ "stamp.done": "Stamped {store}: model={model} dim={dim} digest={digest} ({size} bytes)",
25
+ "check.status": "status: {status} min_cos={min_cos} mean_cos={mean_cos}",
26
+ "check.models": "stored model: {stored} current model: {current}",
27
+ "check.reasons": "reasons:",
28
+ "check.hint.same": "The embedder matches the index.",
29
+ "check.hint.drift": "Close to the stored model but not identical; queries still work, results may shift.",
30
+ "check.hint.different": "The embedder does not match the index. Use the original model or run `embedstamp migrate`.",
31
+ "check.nofp": "No fingerprint found in {store}. Run `embedstamp stamp` while the index still matches its model.",
32
+ "reason.dim_changed": "vector dimension changed",
33
+ "reason.model_name_changed": "model name changed",
34
+ "reason.doc_prefix_changed": "document prefix changed",
35
+ "reason.query_prefix_changed": "query prefix changed",
36
+ "reason.norm_changed": "vector length (norm) changed",
37
+ "reason.normalization_changed": "normalisation changed",
38
+ "reason.probe_cosine_low": "probe sentences point in unrelated directions",
39
+ "reason.probe_cosine_drift": "probe sentences moved slightly",
40
+ "reason.probe_set_changed": "probe sentence set changed",
41
+ "show.title": "Fingerprint in {store}",
42
+ "show.model": "model: {model}",
43
+ "show.dim": "dimensions: {dim} dtype: {dtype}",
44
+ "show.norm": "normalized: {normalized} mean norm: {norm_mean}",
45
+ "show.prefixes": "doc prefix: {doc_prefix!r} query prefix: {query_prefix!r}",
46
+ "show.probes": "probe set: {probe_set} ({n_probes} sentences, {mode})",
47
+ "show.digest": "digest: {digest}",
48
+ "show.created": "created: {created_at}",
49
+ "migrate.start": "Re-embedding {store} with {model} ...",
50
+ "migrate.progress": " {done}/{total} documents",
51
+ "migrate.report": "docs={n_docs} embedded={n_embedded} skipped={n_skipped} green={green}",
52
+ "migrate.self_recall": "self-recall@{k}={value}",
53
+ "migrate.overlap": "overlap@{k} between old and new results={value}",
54
+ "migrate.switched": "switched: {store} now serves {model}; old data kept as {blue}",
55
+ "migrate.not_switched": "Not switched; {green} is ready. Re-run with --switch to make it live.",
56
+ "migrate.refused": "Refused to switch: {message}",
57
+ "err.generic": "error: {message}",
58
+ "mock.banner": "[practice mock] Fake embedders, no model and no network. The numbers are not those of real models.",
59
+ "demo.step1": "1/5 Build a {n}-document index with model {model} ({dim} dims) and stamp it.",
60
+ "demo.stamped": " fingerprint: model={model} dim={dim} digest={digest}",
61
+ "demo.step2": "2/5 Swap the embedder to {model} ({dim} dims, like before) and run {n} fixed queries.",
62
+ "demo.noerror": " No error was raised. Results simply changed.",
63
+ "demo.overlap": " overlap@{k} with the original results: {value} (the original model against itself: {baseline})",
64
+ "demo.step3": "3/5 Check the index fingerprint with the new embedder.",
65
+ "demo.guard": " A Guard would raise EmbeddingMismatchError before the first query.",
66
+ "demo.step4": "4/5 Re-embed every document with {model} into a green collection (migrate).",
67
+ "demo.step5": "5/5 Switch names so the green collection goes live.",
68
+ "demo.done": "Done. The same flow works on Chroma with ChromaStore; see the README.",
69
+ "help.usage": "usage",
70
+ "help.positional": "positional arguments",
71
+ "help.options": "options",
72
+ "help.help": "show this help message and exit",
73
+ "help.version": "show the version and exit",
74
+ "err.not_migratable": "this store cannot be migrated; use local://<dir> or chroma://<db_dir>/<collection>",
75
+ "err.empty_source": "{store} has no documents, so there is nothing to re-embed. migrate copies the documents of an existing index; `embedstamp stamp` only writes the fingerprint and the CLI cannot add documents. Add them with your vector store or LocalIndex.add(...) first (see examples/migrate_local.py), or point --store at a filled index such as chroma://<db_dir>/<collection>.",
76
+ "migrate.reused": "Every document was already in {green} from an earlier run; nothing was re-embedded.",
77
+ "argparse.error": "%(prog)s: error: %(message)s\n",
78
+ "argparse.usage": "usage: ",
79
+ "argparse.heading": "%(heading)s:",
80
+ "argparse.default": " (default: %(default)s)",
81
+ "argparse.subcommands": "subcommands",
82
+ "argparse.argument": "argument %(argument_name)s: %(message)s",
83
+ "argparse.required": "the following arguments are required: %s",
84
+ "argparse.one_of_required": "one of the arguments %s is required",
85
+ "argparse.unrecognized": "unrecognized arguments: %s",
86
+ "argparse.invalid_type": "invalid %(type)s value: %(value)r",
87
+ "argparse.invalid_choice": "invalid choice: %(value)r (choose from %(choices)s)",
88
+ "argparse.unknown_parser": "unknown parser %(parser_name)r (choices: %(choices)s)",
89
+ "argparse.expected_one": "expected one argument",
90
+ "argparse.expected_at_most_one": "expected at most one argument",
91
+ "argparse.expected_at_least_one": "expected at least one argument",
92
+ "argparse.expected_n": "expected %s argument",
93
+ "argparse.expected_n_plural": "expected %s arguments",
94
+ "argparse.ambiguous": "ambiguous option: %(option)s could match %(matches)s",
95
+ "argparse.not_allowed_with": "not allowed with argument %s",
96
+ "argparse.ignored_explicit": "ignored explicit argument %r",
97
+ "argparse.unexpected_option": "unexpected option string: %s",
98
+ "argparse.cant_open": "can't open '%(filename)s': %(error)s"
99
+ }
@@ -0,0 +1,99 @@
1
+ {
2
+ "app.description": "벡터 인덱스에 임베딩 모델의 지문을 찍어 두고, 질의 전에 확인하고, 안전하게 다시 임베딩합니다.",
3
+ "app.epilog": "check 종료 코드: 0 same, 10 drift, 11 different, 12 지문 없음. migrate: 13 전환 거부. 그 밖: 1 오류, 2 사용법 오류, 4 저장 실패.",
4
+ "cmd.demo": "오프라인 연습 데모를 실행합니다(목 임베더, 네트워크 없음).",
5
+ "cmd.stamp": "임베더의 지문을 저장소에 기록합니다.",
6
+ "cmd.check": "임베더를 저장된 지문과 비교합니다.",
7
+ "cmd.show": "저장된 지문을 보여 줍니다.",
8
+ "cmd.migrate": "인덱스를 green 컬렉션에 다시 임베딩하고 품질을 보고하며, 원하면 전환합니다.",
9
+ "opt.lang": "출력 언어: en 또는 ko (기본: EMBEDSTAMP_LANG, 다음 LC_ALL, LC_MESSAGES, LANG).",
10
+ "opt.store": "저장소 명세: local://<디렉터리>, sidecar://<파일>, chroma://<db 디렉터리>/<컬렉션>.",
11
+ "opt.embedder": "임베더 명세: fake:<이름>[?noise=..&scale=..&prefix=..&dim=..] 또는 fastembed:<모델>.",
12
+ "opt.model": "기록할 모델 이름(기본: 임베더 명세에서 가져옴).",
13
+ "opt.doc_prefix": "문서(와 탐침 문장) 앞에 붙이는 접두어.",
14
+ "opt.query_prefix": "질의 앞에 붙이는 접두어.",
15
+ "opt.compact": "32차원 요약만 저장합니다(작지만 덜 정밀).",
16
+ "opt.json": "기계가 읽는 JSON 으로 출력합니다.",
17
+ "opt.to": "새 모델의 임베더 명세.",
18
+ "opt.from": "옛 모델의 임베더 명세(top-k 겹침률 측정을 켭니다).",
19
+ "opt.queries": "겹침률 측정에 쓸 질의가 한 줄에 하나씩 든 텍스트 파일.",
20
+ "opt.k": "자기 회수율과 겹침률에 쓰는 top-k(기본 10).",
21
+ "opt.switch": "다시 임베딩한 뒤 이름을 전환합니다(없으면 옛 인덱스가 그대로 운영됩니다).",
22
+ "opt.batch_size": "한 번에 임베딩하는 문서 수(기본 64).",
23
+ "opt.min_self_recall": "이 자기 회수율 미만이면 전환을 거부합니다(기본 0.9).",
24
+ "stamp.done": "{store} 에 지문을 기록했습니다: model={model} dim={dim} digest={digest} ({size} 바이트)",
25
+ "check.status": "status: {status} min_cos={min_cos} mean_cos={mean_cos}",
26
+ "check.models": "저장된 모델: {stored} 현재 모델: {current}",
27
+ "check.reasons": "사유:",
28
+ "check.hint.same": "임베더가 인덱스와 일치합니다.",
29
+ "check.hint.drift": "저장된 모델과 가깝지만 똑같지는 않습니다. 질의는 되지만 결과가 조금 달라질 수 있습니다.",
30
+ "check.hint.different": "임베더가 인덱스와 맞지 않습니다. 원래 모델을 쓰거나 `embedstamp migrate` 를 실행하세요.",
31
+ "check.nofp": "{store} 에 지문이 없습니다. 인덱스가 모델과 맞는 지금 `embedstamp stamp` 를 실행하세요.",
32
+ "reason.dim_changed": "벡터 차원이 바뀜",
33
+ "reason.model_name_changed": "모델 이름이 바뀜",
34
+ "reason.doc_prefix_changed": "문서 접두어가 바뀜",
35
+ "reason.query_prefix_changed": "질의 접두어가 바뀜",
36
+ "reason.norm_changed": "벡터 길이(노름)가 바뀜",
37
+ "reason.normalization_changed": "정규화 여부가 바뀜",
38
+ "reason.probe_cosine_low": "탐침 문장이 서로 무관한 방향을 가리킴",
39
+ "reason.probe_cosine_drift": "탐침 문장이 조금 움직임",
40
+ "reason.probe_set_changed": "탐침 문장 세트가 바뀜",
41
+ "show.title": "{store} 의 지문",
42
+ "show.model": "모델: {model}",
43
+ "show.dim": "차원: {dim} dtype: {dtype}",
44
+ "show.norm": "정규화: {normalized} 평균 노름: {norm_mean}",
45
+ "show.prefixes": "문서 접두어: {doc_prefix!r} 질의 접두어: {query_prefix!r}",
46
+ "show.probes": "탐침 세트: {probe_set} (문장 {n_probes}개, {mode})",
47
+ "show.digest": "다이제스트: {digest}",
48
+ "show.created": "생성 시각: {created_at}",
49
+ "migrate.start": "{store} 을(를) {model} 로 다시 임베딩하는 중 ...",
50
+ "migrate.progress": " 문서 {done}/{total}",
51
+ "migrate.report": "docs={n_docs} embedded={n_embedded} skipped={n_skipped} green={green}",
52
+ "migrate.self_recall": "self-recall@{k}={value}",
53
+ "migrate.overlap": "옛 결과와 새 결과의 overlap@{k}={value}",
54
+ "migrate.switched": "switched: {store} 이(가) 이제 {model} 로 운영됩니다. 옛 데이터는 {blue} 로 보존",
55
+ "migrate.not_switched": "전환하지 않았습니다. {green} 이(가) 준비됐습니다. 적용하려면 --switch 로 다시 실행하세요.",
56
+ "migrate.refused": "전환을 거부했습니다: {message}",
57
+ "err.generic": "오류: {message}",
58
+ "mock.banner": "[연습용 목] 가짜 임베더입니다. 모델도 네트워크도 쓰지 않으며 수치는 실제 모델과 다릅니다.",
59
+ "demo.step1": "1/5 모델 {model}({dim}차원)로 문서 {n}개짜리 인덱스를 만들고 지문을 찍습니다.",
60
+ "demo.stamped": " 지문: model={model} dim={dim} digest={digest}",
61
+ "demo.step2": "2/5 임베더를 {model}({dim}차원, 이전과 같은 차원)로 바꾸고 고정 질의 {n}개를 실행합니다.",
62
+ "demo.noerror": " 오류는 나지 않았습니다. 결과만 조용히 바뀌었습니다.",
63
+ "demo.overlap": " 원래 결과와의 overlap@{k}: {value} (원래 모델끼리 비교하면 {baseline})",
64
+ "demo.step3": "3/5 새 임베더로 인덱스 지문을 확인합니다.",
65
+ "demo.guard": " Guard 를 쓰면 첫 질의 전에 EmbeddingMismatchError 가 발생합니다.",
66
+ "demo.step4": "4/5 모든 문서를 {model} 로 green 컬렉션에 다시 임베딩합니다(migrate).",
67
+ "demo.step5": "5/5 이름을 바꿔 green 컬렉션을 운영으로 올립니다.",
68
+ "demo.done": "끝났습니다. Chroma 에서는 ChromaStore 로 같은 흐름을 쓸 수 있습니다. README 를 보세요.",
69
+ "help.usage": "사용법",
70
+ "help.positional": "위치 인자",
71
+ "help.options": "옵션",
72
+ "help.help": "이 도움말을 보여 주고 끝냅니다",
73
+ "help.version": "버전을 보여 주고 끝냅니다",
74
+ "err.not_migratable": "이 저장소는 마이그레이션할 수 없습니다. local://<디렉터리> 또는 chroma://<db 디렉터리>/<컬렉션> 을 쓰세요",
75
+ "err.empty_source": "{store} 에 문서가 없어 다시 임베딩할 것이 없습니다. migrate 는 이미 있는 인덱스의 문서를 옮기는 명령이고, `embedstamp stamp` 는 지문만 기록하며 CLI 로는 문서를 넣을 수 없습니다. 먼저 쓰고 있는 벡터 저장소나 LocalIndex.add(...) 로 문서를 넣거나(examples/migrate_local.py 참고), --store 를 chroma://<db 디렉터리>/<컬렉션> 처럼 문서가 있는 인덱스로 지정하세요.",
76
+ "migrate.reused": "{green} 의 문서는 이전 실행에서 모두 임베딩돼 있어 다시 임베딩하지 않았습니다.",
77
+ "argparse.error": "%(prog)s: 오류: %(message)s\n",
78
+ "argparse.usage": "사용법: ",
79
+ "argparse.heading": "%(heading)s:",
80
+ "argparse.default": " (기본값: %(default)s)",
81
+ "argparse.subcommands": "하위 명령",
82
+ "argparse.argument": "인자 %(argument_name)s: %(message)s",
83
+ "argparse.required": "다음 인자가 꼭 필요합니다: %s",
84
+ "argparse.one_of_required": "인자 %s 중 하나가 꼭 필요합니다",
85
+ "argparse.unrecognized": "알 수 없는 인자: %s",
86
+ "argparse.invalid_type": "%(type)s 값이 올바르지 않습니다: %(value)r",
87
+ "argparse.invalid_choice": "고를 수 없는 값: %(value)r (가능한 값: %(choices)s)",
88
+ "argparse.unknown_parser": "알 수 없는 하위 명령 %(parser_name)r (가능한 값: %(choices)s)",
89
+ "argparse.expected_one": "값이 하나 있어야 합니다",
90
+ "argparse.expected_at_most_one": "값은 많아야 하나입니다",
91
+ "argparse.expected_at_least_one": "값이 하나 이상 있어야 합니다",
92
+ "argparse.expected_n": "값이 %s개 있어야 합니다",
93
+ "argparse.expected_n_plural": "값이 %s개 있어야 합니다",
94
+ "argparse.ambiguous": "모호한 옵션: %(option)s 는 %(matches)s 중 무엇인지 알 수 없습니다",
95
+ "argparse.not_allowed_with": "인자 %s 와 함께 쓸 수 없습니다",
96
+ "argparse.ignored_explicit": "무시된 명시적 인자 %r",
97
+ "argparse.unexpected_option": "예상하지 못한 옵션 문자열: %s",
98
+ "argparse.cant_open": "'%(filename)s' 를 열 수 없습니다: %(error)s"
99
+ }
embedstamp/migrate.py ADDED
@@ -0,0 +1,175 @@
1
+ """Blue/green re-embedding: build a new collection with the new model, measure it, then switch."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from collections.abc import Callable, Sequence
7
+ from dataclasses import dataclass
8
+
9
+ import numpy as np
10
+
11
+ from ._vectors import Embedder, as_matrix
12
+ from .errors import EmbedstampError, SwitchRefusedError
13
+ from .fingerprint import Fingerprint, stamp
14
+ from .stores import Doc, MigratableStore
15
+ from .verify import Verdict, verify
16
+
17
+ _SAMPLE_LIMIT = 100
18
+
19
+ EMPTY_SOURCE_MESSAGE = (
20
+ "the source index is empty; there is nothing to migrate. migrate() copies the documents of an "
21
+ "existing index, so add them first (LocalIndex.add(...) or your vector store's add) and run it again"
22
+ )
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class MigrationReport:
27
+ """What migrate() did and how good the new collection is."""
28
+
29
+ n_docs: int
30
+ n_embedded: int
31
+ n_skipped: int
32
+ k: int
33
+ self_recall_at_k: float
34
+ overlap_at_k: float | None
35
+ green_name: str
36
+ blue_name: str | None
37
+ switched: bool
38
+ status_after_switch: str | None
39
+ fingerprint: Fingerprint
40
+ seconds: float
41
+ # 전환 직후 다시 잰 판정(숫자 포함). 전환하지 않았으면 None.
42
+ verdict_after_switch: Verdict | None = None
43
+ # green 컬렉션을 만든 이름(예: docs__green). 전환하면 green_name 은 원래 이름(docs)이 된다.
44
+ built_name: str = ""
45
+
46
+
47
+ def overlap_at_k(a: Sequence[str], b: Sequence[str], k: int) -> float:
48
+ """Share of the top-``k`` ids that two result lists have in common (0..1)."""
49
+ return len(set(a[:k]) & set(b[:k])) / k
50
+
51
+
52
+ def migrate(
53
+ source: MigratableStore,
54
+ new_embed: Embedder,
55
+ *,
56
+ new_model: str,
57
+ target_name: str | None = None,
58
+ old_embed: Embedder | None = None,
59
+ queries: Sequence[str] | None = None,
60
+ k: int = 10,
61
+ batch_size: int = 64,
62
+ switch: bool = False,
63
+ doc_prefix: str = "",
64
+ query_prefix: str = "",
65
+ old_query_prefix: str = "",
66
+ min_self_recall: float = 0.9,
67
+ compact: bool = False,
68
+ progress: Callable[[int, int], None] | None = None,
69
+ ) -> MigrationReport:
70
+ """Re-embed every document of ``source`` into a new collection with ``new_embed``.
71
+
72
+ 1. Create (or resume) the green collection ``target_name`` (default ``<name>__green``).
73
+ 2. Embed documents in batches; ids already present in green are skipped, so a re-run after
74
+ a crash continues where it stopped.
75
+ 3. Measure self-recall@k (documents found by their own text) and, when ``old_embed`` is
76
+ given, the top-k overlap between old and new results for ``queries``.
77
+ 4. Only with ``switch=True`` (and self-recall >= ``min_self_recall``): rename so that green
78
+ takes the original name; the old data stays as ``<name>__blue_<date>``.
79
+ """
80
+ if k < 1 or batch_size < 1:
81
+ raise ValueError("k and batch_size must be >= 1")
82
+ started = time.monotonic()
83
+ n_docs = source.count()
84
+ if n_docs == 0:
85
+ raise EmbedstampError(EMPTY_SOURCE_MESSAGE)
86
+
87
+ green = source.create_sibling(target_name or f"{source.name}__green")
88
+ existing_fp = green.load()
89
+ if existing_fp is not None:
90
+ verdict = verify(existing_fp, new_embed, model=new_model, doc_prefix=doc_prefix,
91
+ query_prefix=query_prefix)
92
+ if verdict.status == "different":
93
+ raise EmbedstampError(
94
+ f"collection {green.name!r} already holds vectors from a different model "
95
+ f"({existing_fp.model!r}); delete it or choose another target_name"
96
+ )
97
+ elif green.count() > 0:
98
+ raise EmbedstampError(
99
+ f"collection {green.name!r} is not empty and has no fingerprint, so its model is "
100
+ "unknown; delete it or choose another target_name"
101
+ )
102
+ else:
103
+ green.save(stamp(new_embed, model=new_model, doc_prefix=doc_prefix,
104
+ query_prefix=query_prefix, compact=compact))
105
+
106
+ done = green.existing_ids()
107
+ n_embedded = n_skipped = 0
108
+ stride = max(1, n_docs // _SAMPLE_LIMIT)
109
+ sample: list[Doc] = []
110
+ seen = 0
111
+ for batch in source.iter_documents(batch_size):
112
+ todo = [d for d in batch if d.id not in done]
113
+ n_skipped += len(batch) - len(todo)
114
+ if todo:
115
+ vectors = as_matrix(new_embed([doc_prefix + d.text for d in todo]), len(todo))
116
+ green.add([d.id for d in todo], [d.text for d in todo], vectors, [d.metadata for d in todo])
117
+ n_embedded += len(todo)
118
+ for d in batch:
119
+ if seen % stride == 0 and len(sample) < _SAMPLE_LIMIT:
120
+ sample.append(d)
121
+ seen += 1
122
+ if progress:
123
+ progress(n_embedded + n_skipped, n_docs)
124
+
125
+ probe_texts = [query_prefix + d.text for d in sample]
126
+ sample_vecs = as_matrix(new_embed(probe_texts), len(probe_texts))
127
+ hits = sum(d.id in green.query(v, k) for d, v in zip(sample, sample_vecs))
128
+ self_recall = hits / len(sample)
129
+
130
+ overlap: float | None = None
131
+ if old_embed is not None:
132
+ qtexts = list(queries) if queries else [d.text for d in sample]
133
+ old_vecs = as_matrix(old_embed([old_query_prefix + q for q in qtexts]), len(qtexts))
134
+ new_vecs = as_matrix(new_embed([query_prefix + q for q in qtexts]), len(qtexts))
135
+ overlap = float(np.mean([
136
+ overlap_at_k(source.query(o, k), green.query(n, k), k)
137
+ for o, n in zip(old_vecs, new_vecs)
138
+ ]))
139
+
140
+ new_fp = green.load()
141
+ assert new_fp is not None # stamped above or on a previous run
142
+ blue_label: str | None = None
143
+ switched = False
144
+ status_after: str | None = None
145
+ green_label = green.name
146
+ report = MigrationReport(
147
+ n_docs=n_docs, n_embedded=n_embedded, n_skipped=n_skipped, k=k,
148
+ self_recall_at_k=self_recall, overlap_at_k=overlap, green_name=green_label,
149
+ blue_name=None, switched=False, status_after_switch=None, fingerprint=new_fp,
150
+ seconds=time.monotonic() - started, built_name=green_label,
151
+ )
152
+ if switch:
153
+ if self_recall < min_self_recall:
154
+ raise SwitchRefusedError(
155
+ f"self-recall@{k} is {self_recall:.2f}, below the required {min_self_recall:.2f}; "
156
+ f"collection {green_label!r} was kept but not switched. Check the embedder and prefixes.",
157
+ report,
158
+ )
159
+ blue_label = source.switch_to(green)
160
+ switched = True
161
+ # 전환 뒤 원래 이름에 실린 지문을 새 임베더로 다시 재서, 상태와 수치를 함께 보고한다
162
+ live_fp = source.load()
163
+ verdict_after: Verdict | None = None
164
+ if live_fp is not None:
165
+ verdict_after = verify(live_fp, new_embed, model=new_model, doc_prefix=doc_prefix,
166
+ query_prefix=query_prefix)
167
+ status_after = verdict_after.status
168
+ report = MigrationReport(
169
+ n_docs=n_docs, n_embedded=n_embedded, n_skipped=n_skipped, k=k,
170
+ self_recall_at_k=self_recall, overlap_at_k=overlap, green_name=source.name,
171
+ blue_name=blue_label, switched=switched, status_after_switch=status_after,
172
+ fingerprint=new_fp, seconds=time.monotonic() - started,
173
+ verdict_after_switch=verdict_after, built_name=green_label,
174
+ )
175
+ return report
embedstamp/probes.py ADDED
@@ -0,0 +1,38 @@
1
+ """Fixed probe sentences. Embedding the same sentences again reveals whether the model changed."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from collections.abc import Sequence
7
+
8
+ DEFAULT_PROBE_SET = "default-v1"
9
+
10
+ # Mixed English, Korean, numbers and code so that tokenizer or language-coverage changes show up.
11
+ DEFAULT_PROBES: tuple[str, ...] = (
12
+ "The quick brown fox jumps over the lazy dog.",
13
+ "How do I reset my password?",
14
+ "서울에서 부산까지 KTX로 약 두 시간 반이 걸린다.",
15
+ "Invoice #4821 is due on 2026-03-31 for $1,250.00.",
16
+ "def add(a, b): return a + b",
17
+ "Photosynthesis converts light energy into chemical energy.",
18
+ "오늘 회의는 오후 세 시에 시작합니다.",
19
+ "A vector index stores embeddings for similarity search.",
20
+ )
21
+
22
+
23
+ def probe_set_id(probes: Sequence[str] | None) -> str:
24
+ """Return the id of a probe set: ``default-v1`` or ``sha256:<12 hex>`` for custom sets."""
25
+ if probes is None or tuple(probes) == DEFAULT_PROBES:
26
+ return DEFAULT_PROBE_SET
27
+ digest = hashlib.sha256("\x1f".join(probes).encode("utf-8")).hexdigest()[:12]
28
+ return f"sha256:{digest}"
29
+
30
+
31
+ def resolve_probes(probes: Sequence[str] | None) -> tuple[str, ...]:
32
+ """Return the probe sentences to use, validating custom sets."""
33
+ if probes is None:
34
+ return DEFAULT_PROBES
35
+ items = tuple(probes)
36
+ if len(items) < 2 or any(not isinstance(p, str) or not p.strip() for p in items):
37
+ raise ValueError("probes must be at least 2 non-empty strings")
38
+ return items
embedstamp/py.typed ADDED
File without changes
@@ -0,0 +1,93 @@
1
+ """Storage adapters: where fingerprints live, and what migrate() needs from an index."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator, Sequence
6
+ from dataclasses import dataclass, field
7
+ from datetime import datetime, timezone
8
+ from typing import Any, Protocol, runtime_checkable
9
+
10
+ import numpy as np
11
+
12
+ from ..fingerprint import Fingerprint
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Doc:
17
+ """One stored document."""
18
+
19
+ id: str
20
+ text: str
21
+ metadata: dict[str, Any] = field(default_factory=dict)
22
+
23
+
24
+ @runtime_checkable
25
+ class FingerprintStore(Protocol):
26
+ """Anything that can keep one fingerprint."""
27
+
28
+ def load(self) -> Fingerprint | None: ...
29
+
30
+ def save(self, fp: Fingerprint) -> None: ...
31
+
32
+
33
+ @runtime_checkable
34
+ class MigratableStore(FingerprintStore, Protocol):
35
+ """An index that migrate() can copy into a new collection and switch."""
36
+
37
+ name: str
38
+
39
+ def iter_documents(self, batch_size: int = 64) -> Iterator[list[Doc]]: ...
40
+
41
+ def create_sibling(self, name: str) -> "MigratableStore": ...
42
+
43
+ def add(
44
+ self,
45
+ ids: Sequence[str],
46
+ texts: Sequence[str],
47
+ vectors: np.ndarray,
48
+ metadatas: Sequence[dict[str, Any]] | None = None,
49
+ ) -> None: ...
50
+
51
+ def query(self, vector: np.ndarray, k: int = 10) -> list[str]: ...
52
+
53
+ def existing_ids(self) -> set[str]: ...
54
+
55
+ def count(self) -> int: ...
56
+
57
+ def switch_to(self, sibling: "MigratableStore") -> str:
58
+ """Keep this index under a ``__blue_<date>`` name, make ``sibling`` live; return the blue name."""
59
+ ...
60
+
61
+
62
+ def blue_name(name: str, taken: set[str] | None = None) -> str:
63
+ """Name under which the previous live collection is kept: ``<name>__blue_<YYYYMMDD>``."""
64
+ base = f"{name}__blue_{datetime.now(timezone.utc):%Y%m%d}"
65
+ candidate, n = base, 2
66
+ while taken and candidate in taken:
67
+ candidate, n = f"{base}_{n}", n + 1
68
+ return candidate
69
+
70
+
71
+ def resolve_store(spec: str) -> FingerprintStore:
72
+ """Open a store from a spec: ``local://<dir>``, ``sidecar://<file>`` or ``chroma://<db_dir>/<collection>``."""
73
+ scheme, sep, rest = spec.partition("://")
74
+ if not sep or not rest:
75
+ raise ValueError(
76
+ f"invalid store spec {spec!r}; use local://<dir>, sidecar://<file> or chroma://<db_dir>/<collection>"
77
+ )
78
+ if scheme == "local":
79
+ from .local import LocalIndex
80
+
81
+ return LocalIndex(rest)
82
+ if scheme == "sidecar":
83
+ from .sidecar import SidecarStore
84
+
85
+ return SidecarStore(rest)
86
+ if scheme == "chroma":
87
+ from .chroma import ChromaStore
88
+
89
+ db_dir, slash, collection = rest.rpartition("/")
90
+ if not slash or not db_dir or not collection:
91
+ raise ValueError("chroma spec must look like chroma://<db_dir>/<collection>")
92
+ return ChromaStore.open(db_dir, collection)
93
+ raise ValueError(f"unknown store scheme {scheme!r}; use local, sidecar or chroma")