harborrag-core 2.0.0__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.
Files changed (161) hide show
  1. harborrag_core/__init__.py +29 -0
  2. harborrag_core/base.py +126 -0
  3. harborrag_core/chunking/__init__.py +70 -0
  4. harborrag_core/chunking/errors.py +6 -0
  5. harborrag_core/chunking/identity.py +209 -0
  6. harborrag_core/chunking/metadata.py +61 -0
  7. harborrag_core/chunking/record.py +164 -0
  8. harborrag_core/chunking/schemas.py +292 -0
  9. harborrag_core/chunking/source_schemas.py +102 -0
  10. harborrag_core/chunking/table_schemas.py +73 -0
  11. harborrag_core/chunking/tokenization.py +28 -0
  12. harborrag_core/config_store/__init__.py +51 -0
  13. harborrag_core/config_store/documents.py +178 -0
  14. harborrag_core/config_store/durations.py +32 -0
  15. harborrag_core/config_store/levels.py +83 -0
  16. harborrag_core/config_store/registry.py +456 -0
  17. harborrag_core/config_store/resolution.py +260 -0
  18. harborrag_core/contracts/__init__.py +53 -0
  19. harborrag_core/contracts/chunking.py +134 -0
  20. harborrag_core/contracts/errors.py +219 -0
  21. harborrag_core/contracts/events.py +31 -0
  22. harborrag_core/contracts/reader.py +777 -0
  23. harborrag_core/contracts/tools.py +54 -0
  24. harborrag_core/domain/__init__.py +42 -0
  25. harborrag_core/domain/activity.py +28 -0
  26. harborrag_core/domain/connection.py +277 -0
  27. harborrag_core/domain/connection_paging.py +57 -0
  28. harborrag_core/domain/connection_snapshot.py +96 -0
  29. harborrag_core/domain/document.py +205 -0
  30. harborrag_core/domain/element.py +26 -0
  31. harborrag_core/domain/graph_conflict.py +34 -0
  32. harborrag_core/domain/identity.py +81 -0
  33. harborrag_core/domain/job.py +53 -0
  34. harborrag_core/domain/member.py +46 -0
  35. harborrag_core/domain/parser.py +57 -0
  36. harborrag_core/domain/pending_effect.py +26 -0
  37. harborrag_core/domain/project.py +43 -0
  38. harborrag_core/domain/provenance.py +21 -0
  39. harborrag_core/domain/provider.py +31 -0
  40. harborrag_core/domain/raw_document.py +21 -0
  41. harborrag_core/domain/retrieval.py +27 -0
  42. harborrag_core/domain/settings.py +20 -0
  43. harborrag_core/domain/source.py +17 -0
  44. harborrag_core/domain/table.py +171 -0
  45. harborrag_core/domain/validation.py +139 -0
  46. harborrag_core/indexing/__init__.py +61 -0
  47. harborrag_core/ingestion/__init__.py +226 -0
  48. harborrag_core/ingestion/artifact_contracts.py +111 -0
  49. harborrag_core/ingestion/canonical_codec.py +101 -0
  50. harborrag_core/ingestion/comments.py +42 -0
  51. harborrag_core/ingestion/connector_contracts.py +138 -0
  52. harborrag_core/ingestion/errors.py +77 -0
  53. harborrag_core/ingestion/graph_attribute_validation.py +156 -0
  54. harborrag_core/ingestion/graph_taxonomy.py +57 -0
  55. harborrag_core/ingestion/identity.py +423 -0
  56. harborrag_core/ingestion/lifecycle_contracts.py +154 -0
  57. harborrag_core/ingestion/limits.py +47 -0
  58. harborrag_core/ingestion/policies.py +358 -0
  59. harborrag_core/ingestion/projection_contracts.py +188 -0
  60. harborrag_core/ingestion/projection_graph.py +200 -0
  61. harborrag_core/ingestion/projection_vector.py +317 -0
  62. harborrag_core/ingestion/representations.py +79 -0
  63. harborrag_core/ingestion/run_contracts.py +303 -0
  64. harborrag_core/ingestion/source_catalog.py +58 -0
  65. harborrag_core/ingestion/source_contracts.py +119 -0
  66. harborrag_core/ingestion/source_query.py +95 -0
  67. harborrag_core/ingestion/stages.py +97 -0
  68. harborrag_core/ingestion/states.py +220 -0
  69. harborrag_core/ingestion/task_query_contracts.py +72 -0
  70. harborrag_core/invariants.py +22 -0
  71. harborrag_core/models/__init__.py +183 -0
  72. harborrag_core/models/capabilities.py +59 -0
  73. harborrag_core/models/chat/__init__.py +47 -0
  74. harborrag_core/models/chat/content.py +85 -0
  75. harborrag_core/models/chat/enums.py +59 -0
  76. harborrag_core/models/chat/messages.py +85 -0
  77. harborrag_core/models/chat/requests.py +91 -0
  78. harborrag_core/models/chat/responses.py +90 -0
  79. harborrag_core/models/chat/tools.py +40 -0
  80. harborrag_core/models/context.py +21 -0
  81. harborrag_core/models/embed.py +148 -0
  82. harborrag_core/models/errors.py +273 -0
  83. harborrag_core/models/headers.py +31 -0
  84. harborrag_core/models/metadata.py +15 -0
  85. harborrag_core/models/rerank.py +136 -0
  86. harborrag_core/models/usage.py +11 -0
  87. harborrag_core/observability/__init__.py +0 -0
  88. harborrag_core/observability/process_logging.py +77 -0
  89. harborrag_core/ports/__init__.py +102 -0
  90. harborrag_core/ports/api_keys.py +54 -0
  91. harborrag_core/ports/artifacts.py +178 -0
  92. harborrag_core/ports/completion_requests.py +77 -0
  93. harborrag_core/ports/config_store.py +93 -0
  94. harborrag_core/ports/control_plane.py +364 -0
  95. harborrag_core/ports/conversation.py +436 -0
  96. harborrag_core/ports/conversation_leases.py +33 -0
  97. harborrag_core/ports/description_generation.py +42 -0
  98. harborrag_core/ports/document_release.py +171 -0
  99. harborrag_core/ports/events.py +30 -0
  100. harborrag_core/ports/indexing.py +185 -0
  101. harborrag_core/ports/memory.py +277 -0
  102. harborrag_core/ports/model_catalog.py +123 -0
  103. harborrag_core/ports/model_clients.py +221 -0
  104. harborrag_core/ports/reader.py +54 -0
  105. harborrag_core/ports/retrieval.py +47 -0
  106. harborrag_core/ports/secrets.py +28 -0
  107. harborrag_core/ports/storage.py +114 -0
  108. harborrag_core/ports/summary_projection.py +121 -0
  109. harborrag_core/ports/tenant_directory.py +29 -0
  110. harborrag_core/ports/tools.py +16 -0
  111. harborrag_core/ports/topology.py +220 -0
  112. harborrag_core/ports/topology_extraction.py +45 -0
  113. harborrag_core/ports/topology_projection.py +18 -0
  114. harborrag_core/ports/usage.py +96 -0
  115. harborrag_core/retrieval/__init__.py +39 -0
  116. harborrag_core/retrieval/graph.py +267 -0
  117. harborrag_core/schemas/__init__.py +0 -0
  118. harborrag_core/schemas/graph.py +67 -0
  119. harborrag_core/schemas/ids.py +68 -0
  120. harborrag_core/schemas/object_store.py +61 -0
  121. harborrag_core/schemas/storage.py +99 -0
  122. harborrag_core/schemas/telemetry.py +35 -0
  123. harborrag_core/schemas/vector.py +211 -0
  124. harborrag_core/security/__init__.py +20 -0
  125. harborrag_core/security/api_keys.py +75 -0
  126. harborrag_core/security/context.py +55 -0
  127. harborrag_core/security/field_names.py +132 -0
  128. harborrag_core/security/redaction.py +92 -0
  129. harborrag_core/security/remote_transport.py +73 -0
  130. harborrag_core/security/secret_refs.py +165 -0
  131. harborrag_core/security/url_policy.py +108 -0
  132. harborrag_core/storage/__init__.py +23 -0
  133. harborrag_core/storage/namespace.py +39 -0
  134. harborrag_core/summaries.py +269 -0
  135. harborrag_core/summary_cards.py +137 -0
  136. harborrag_core/testing/chunking.py +47 -0
  137. harborrag_core/testing/control_plane_fakes.py +431 -0
  138. harborrag_core/testing/control_plane_fakes_graph_conflicts.py +108 -0
  139. harborrag_core/testing/fakes.py +135 -0
  140. harborrag_core/testing/graph_fakes.py +325 -0
  141. harborrag_core/topology/__init__.py +57 -0
  142. harborrag_core/topology/budget.py +64 -0
  143. harborrag_core/topology/config.py +51 -0
  144. harborrag_core/topology/derived.py +205 -0
  145. harborrag_core/topology/evaluation.py +46 -0
  146. harborrag_core/topology/evidence.py +68 -0
  147. harborrag_core/topology/extraction.py +253 -0
  148. harborrag_core/topology/ontology.py +110 -0
  149. harborrag_core/topology/output_policy.py +164 -0
  150. harborrag_core/topology/permissions.py +159 -0
  151. harborrag_core/topology/records.py +104 -0
  152. harborrag_core/topology/resolution.py +34 -0
  153. harborrag_core/topology/retrieval_policy.py +23 -0
  154. harborrag_core/topology/revisions.py +37 -0
  155. harborrag_core/topology/search.py +155 -0
  156. harborrag_core/topology/text_policy.py +48 -0
  157. harborrag_core/topology/windowing.py +185 -0
  158. harborrag_core-2.0.0.dist-info/METADATA +87 -0
  159. harborrag_core-2.0.0.dist-info/RECORD +161 -0
  160. harborrag_core-2.0.0.dist-info/WHEEL +4 -0
  161. harborrag_core-2.0.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,29 @@
1
+ from harborrag_core.contracts.errors import HarborError
2
+ from harborrag_core.domain import (
3
+ Document,
4
+ DocumentElement,
5
+ DocumentProvenance,
6
+ DocumentRelation,
7
+ RawDocument,
8
+ RetrievalQuery,
9
+ RetrievalResult,
10
+ SourceRecord,
11
+ )
12
+ from harborrag_core.security.redaction import redact_mapping, redact_secrets
13
+ from harborrag_core.security.url_policy import URLPolicy, URLPolicyError
14
+
15
+ __all__ = [
16
+ "Document",
17
+ "DocumentElement",
18
+ "DocumentProvenance",
19
+ "DocumentRelation",
20
+ "HarborError",
21
+ "RawDocument",
22
+ "RetrievalQuery",
23
+ "RetrievalResult",
24
+ "SourceRecord",
25
+ "URLPolicy",
26
+ "URLPolicyError",
27
+ "redact_mapping",
28
+ "redact_secrets",
29
+ ]
harborrag_core/base.py ADDED
@@ -0,0 +1,126 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from datetime import UTC, datetime
5
+ from functools import cache
6
+ from typing import Any
7
+
8
+ from pydantic import BaseModel, ConfigDict
9
+
10
+
11
+ def utc_now() -> datetime:
12
+ """Return the current timezone-aware UTC timestamp."""
13
+ return datetime.now(UTC)
14
+
15
+
16
+ class StrictModel(BaseModel):
17
+ """Recursively immutable model that rejects unknown fields."""
18
+
19
+ model_config = ConfigDict(extra="forbid", frozen=True)
20
+
21
+ def model_post_init(self, context: Any, /) -> None:
22
+ del context
23
+ for name, value in self.__dict__.items():
24
+ object.__setattr__(self, name, _deep_freeze(value))
25
+ if self.__pydantic_extra__ is not None:
26
+ object.__setattr__(self, "__pydantic_extra__", _deep_freeze(self.__pydantic_extra__))
27
+
28
+
29
+ class ExtensibleModel(BaseModel):
30
+ """Recursively immutable model that preserves provider-specific fields."""
31
+
32
+ model_config = ConfigDict(extra="allow", frozen=True)
33
+
34
+ def model_post_init(self, context: Any, /) -> None:
35
+ del context
36
+ for name, value in self.__dict__.items():
37
+ object.__setattr__(self, name, _deep_freeze(value))
38
+ if self.__pydantic_extra__ is not None:
39
+ object.__setattr__(self, "__pydantic_extra__", _deep_freeze(self.__pydantic_extra__))
40
+
41
+
42
+ class FrozenDict(dict[Any, Any]):
43
+ """A ``dict`` compatible with Pydantic serializers but closed to mutation."""
44
+
45
+ def _immutable(self, *args: object, **kwargs: object) -> None:
46
+ del args, kwargs
47
+ raise TypeError("frozen model containers are immutable")
48
+
49
+ def __copy__(self) -> FrozenDict:
50
+ return self
51
+
52
+ def __deepcopy__(self, memo: dict[int, Any]) -> FrozenDict:
53
+ memo[id(self)] = self
54
+ return self
55
+
56
+ __delitem__ = _immutable
57
+ __ior__ = _immutable # type: ignore[assignment]
58
+ __setitem__ = _immutable
59
+ clear = _immutable
60
+ pop = _immutable
61
+ popitem = _immutable # type: ignore[assignment]
62
+ setdefault = _immutable
63
+ update = _immutable
64
+
65
+
66
+ class FrozenList(list[Any]):
67
+ """A ``list`` compatible with Pydantic serializers but closed to mutation."""
68
+
69
+ def _immutable(self, *args: object, **kwargs: object) -> None:
70
+ del args, kwargs
71
+ raise TypeError("frozen model containers are immutable")
72
+
73
+ def __copy__(self) -> FrozenList:
74
+ return self
75
+
76
+ def __deepcopy__(self, memo: dict[int, Any]) -> FrozenList:
77
+ memo[id(self)] = self
78
+ return self
79
+
80
+ __delitem__ = _immutable
81
+ __iadd__ = _immutable # type: ignore[assignment]
82
+ __imul__ = _immutable # type: ignore[assignment]
83
+ __setitem__ = _immutable
84
+ append = _immutable
85
+ clear = _immutable
86
+ extend = _immutable
87
+ insert = _immutable
88
+ pop = _immutable
89
+ remove = _immutable
90
+ reverse = _immutable
91
+ sort = _immutable
92
+
93
+
94
+ @cache
95
+ def _frozen_metadata_type() -> type:
96
+ """``FrozenMetadata``, imported late to break the cycle back to this module.
97
+
98
+ It is already immutable, so re-wrapping it in a ``FrozenDict`` would lose
99
+ its behaviour. Recognising it by comparing ``__name__`` and ``__module__``
100
+ worked only while the class stayed exactly where it was: moving it, or
101
+ subclassing it, silently resumed re-wrapping. ``chunking.metadata`` imports
102
+ this module, so the import has to happen on first call rather than at
103
+ module scope.
104
+ """
105
+
106
+ from harborrag_core.chunking.metadata import FrozenMetadata
107
+
108
+ return FrozenMetadata
109
+
110
+
111
+ def _deep_freeze(value: Any) -> Any:
112
+ """Freeze nested built-in containers while retaining JSON serialization."""
113
+
114
+ if isinstance(value, BaseModel):
115
+ return value
116
+ if isinstance(value, _frozen_metadata_type()):
117
+ return value
118
+ if isinstance(value, Mapping):
119
+ return FrozenDict({key: _deep_freeze(item) for key, item in value.items()})
120
+ if isinstance(value, list):
121
+ return FrozenList(_deep_freeze(item) for item in value)
122
+ if isinstance(value, tuple):
123
+ return tuple(_deep_freeze(item) for item in value)
124
+ if isinstance(value, (set, frozenset)):
125
+ return frozenset(_deep_freeze(item) for item in value)
126
+ return value
@@ -0,0 +1,70 @@
1
+ from .errors import ChunkContractError, ChunkIdentityError
2
+ from .identity import (
3
+ CanonicalIdentityBuilder,
4
+ canonical_identity_payload,
5
+ content_fingerprint,
6
+ encoded_identifier,
7
+ manifest_fingerprint,
8
+ normalize_identity_text,
9
+ normalize_structural_path,
10
+ )
11
+ from .metadata import ChunkMetadata, FrozenMetadata, thaw_metadata
12
+ from .record import ChunkRecord
13
+ from .schemas import (
14
+ CHUNK_PROPERTIES,
15
+ COMMON_NODE_PROPERTIES,
16
+ DOCUMENT_OWNED_PROPERTIES,
17
+ ENTITY_PROPERTIES,
18
+ PROJECTED_RELATION_TYPES,
19
+ RELATES_PROPERTIES,
20
+ ChunkContainer,
21
+ ChunkHierarchy,
22
+ ChunkKind,
23
+ ChunkQuality,
24
+ ChunkRelation,
25
+ ConnectorType,
26
+ ContainerKind,
27
+ DocumentKind,
28
+ RecordKind,
29
+ RelationType,
30
+ )
31
+ from .source_schemas import ChunkSecurity, CitationLocator, SourceAttribute, SourceLocator
32
+ from .table_schemas import TableChunkLocator, TableProjectionType
33
+
34
+ __all__ = [
35
+ "CHUNK_PROPERTIES",
36
+ "COMMON_NODE_PROPERTIES",
37
+ "ChunkContainer",
38
+ "ChunkContractError",
39
+ "ChunkHierarchy",
40
+ "ChunkIdentityError",
41
+ "ChunkKind",
42
+ "ChunkMetadata",
43
+ "ChunkQuality",
44
+ "ChunkRecord",
45
+ "ChunkRelation",
46
+ "ChunkSecurity",
47
+ "CanonicalIdentityBuilder",
48
+ "CitationLocator",
49
+ "ConnectorType",
50
+ "ContainerKind",
51
+ "DOCUMENT_OWNED_PROPERTIES",
52
+ "DocumentKind",
53
+ "ENTITY_PROPERTIES",
54
+ "FrozenMetadata",
55
+ "PROJECTED_RELATION_TYPES",
56
+ "RELATES_PROPERTIES",
57
+ "RelationType",
58
+ "RecordKind",
59
+ "SourceAttribute",
60
+ "SourceLocator",
61
+ "TableChunkLocator",
62
+ "TableProjectionType",
63
+ "canonical_identity_payload",
64
+ "content_fingerprint",
65
+ "encoded_identifier",
66
+ "manifest_fingerprint",
67
+ "normalize_identity_text",
68
+ "normalize_structural_path",
69
+ "thaw_metadata",
70
+ ]
@@ -0,0 +1,6 @@
1
+ class ChunkContractError(ValueError):
2
+ """Base error for canonical chunk contract operations."""
3
+
4
+
5
+ class ChunkIdentityError(ChunkContractError):
6
+ """Raised when deterministic identity input cannot be normalized safely."""
@@ -0,0 +1,209 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from collections.abc import Iterable, Mapping, Sequence
5
+ from hashlib import sha256
6
+ from re import compile as compile_pattern
7
+ from unicodedata import normalize
8
+
9
+ from harborrag_core.chunking.errors import ChunkContractError, ChunkIdentityError
10
+
11
+ from .schemas import ChunkKind
12
+
13
+ _HORIZONTAL_WHITESPACE = compile_pattern(r"[^\S\n]+")
14
+
15
+
16
+ def normalize_identity_text(value: str) -> str:
17
+ """Normalize text using the stable Work 1 identity policy."""
18
+
19
+ normalized = normalize("NFC", value).replace("\r\n", "\n").replace("\r", "\n")
20
+ lines = [_HORIZONTAL_WHITESPACE.sub(" ", line).strip() for line in normalized.split("\n")]
21
+ while lines and not lines[0]:
22
+ lines.pop(0)
23
+ while lines and not lines[-1]:
24
+ lines.pop()
25
+ compacted: list[str] = []
26
+ for line in lines:
27
+ if line or not compacted or compacted[-1]:
28
+ compacted.append(line)
29
+ return "\n".join(compacted)
30
+
31
+
32
+ def normalize_structural_path(path: Sequence[str]) -> tuple[str, ...]:
33
+ """Normalize an ordered path without changing its case or ancestry."""
34
+
35
+ normalized = tuple(" ".join(normalize("NFC", part).split()) for part in path)
36
+ if any(not part for part in normalized):
37
+ raise ChunkContractError("structural path parts must be non-empty")
38
+ return normalized
39
+
40
+
41
+ def canonical_identity_payload(value: object) -> str:
42
+ """Serialize identity input with normalized strings and sorted mapping keys."""
43
+
44
+ normalized = _normalize_value(value)
45
+ try:
46
+ return json.dumps(
47
+ normalized,
48
+ ensure_ascii=False,
49
+ allow_nan=False,
50
+ separators=(",", ":"),
51
+ sort_keys=True,
52
+ )
53
+ except (TypeError, ValueError) as exc:
54
+ raise ChunkIdentityError("identity input must be finite JSON data") from exc
55
+
56
+
57
+ def encoded_identifier(kind: str, value: object) -> str:
58
+ """Encode one domain-separated identifier as lowercase SHA-256 hex."""
59
+
60
+ if not kind.strip():
61
+ raise ChunkIdentityError("identifier kind must be non-empty")
62
+ payload = canonical_identity_payload({"kind": kind, "value": value})
63
+ return f"{kind}:{sha256(payload.encode('utf-8')).hexdigest()}"
64
+
65
+
66
+ def content_fingerprint(content: str) -> str:
67
+ """Return the SHA-256 fingerprint for normalized evidence content."""
68
+
69
+ normalized = normalize_identity_text(content)
70
+ return sha256(normalized.encode("utf-8")).hexdigest()
71
+
72
+
73
+ def manifest_fingerprint(chunk_ids: Iterable[str]) -> str:
74
+ """Return an order-sensitive fingerprint for chunk revision identities."""
75
+
76
+ return encoded_identifier("chunk-manifest", tuple(chunk_ids))
77
+
78
+
79
+ class CanonicalIdentityBuilder:
80
+ """Build deterministic source-independent canonical identities."""
81
+
82
+ def section_id(
83
+ self,
84
+ *,
85
+ document_id: str,
86
+ section_path: Sequence[str],
87
+ stable_source_anchors: Sequence[str] = (),
88
+ ) -> str:
89
+ return encoded_identifier(
90
+ "section",
91
+ {
92
+ "document_id": document_id,
93
+ "section_path": normalize_structural_path(section_path),
94
+ **(
95
+ {"stable_source_anchors": tuple(stable_source_anchors)}
96
+ if stable_source_anchors
97
+ else {}
98
+ ),
99
+ },
100
+ )
101
+
102
+ def logical_chunk_id(
103
+ self,
104
+ *,
105
+ section_id: str,
106
+ stable_source_range: Mapping[str, object],
107
+ chunk_kind: ChunkKind,
108
+ ) -> str:
109
+ return encoded_identifier(
110
+ "logical-chunk",
111
+ {
112
+ "section_id": section_id,
113
+ "stable_source_range": dict(stable_source_range),
114
+ "chunk_kind": chunk_kind.value,
115
+ },
116
+ )
117
+
118
+ def chunk_id(
119
+ self,
120
+ *,
121
+ logical_chunk_id: str,
122
+ document_version_id: str,
123
+ strategy_version: str,
124
+ content_hash: str,
125
+ ) -> str:
126
+ return encoded_identifier(
127
+ "chunk",
128
+ {
129
+ "logical_chunk_id": logical_chunk_id,
130
+ "document_version_id": document_version_id,
131
+ "strategy_version": strategy_version,
132
+ "content_hash": content_hash,
133
+ },
134
+ )
135
+
136
+ def table_id(
137
+ self,
138
+ *,
139
+ document_id: str,
140
+ section_path: Sequence[str],
141
+ stable_table_location: Mapping[str, object],
142
+ ) -> str:
143
+ return encoded_identifier(
144
+ "table",
145
+ {
146
+ "document_id": document_id,
147
+ "section_path": normalize_structural_path(section_path),
148
+ "stable_table_location": dict(stable_table_location),
149
+ },
150
+ )
151
+
152
+ def table_version_id(
153
+ self,
154
+ *,
155
+ table_id: str,
156
+ source_version: str,
157
+ content_hash: str,
158
+ ) -> str:
159
+ return encoded_identifier(
160
+ "table-version",
161
+ {
162
+ "table_id": table_id,
163
+ "source_version": source_version,
164
+ "content_hash": content_hash,
165
+ },
166
+ )
167
+
168
+ def permission_set_id(
169
+ self,
170
+ *,
171
+ tenant_id: str,
172
+ permissions: Mapping[str, object],
173
+ ) -> str:
174
+ return encoded_identifier(
175
+ "permission-set",
176
+ {"tenant_id": tenant_id, "permissions": dict(permissions)},
177
+ )
178
+
179
+
180
+ def _normalize_value(
181
+ value: object,
182
+ active_containers: set[int] | None = None,
183
+ ) -> object:
184
+ active_containers = set() if active_containers is None else active_containers
185
+ if isinstance(value, str):
186
+ return normalize_identity_text(value)
187
+ if isinstance(value, Mapping):
188
+ if id(value) in active_containers:
189
+ raise ChunkIdentityError("identity input must not contain cycles")
190
+ active_containers = active_containers | {id(value)}
191
+ normalized: dict[str, object] = {}
192
+ for key, item in value.items():
193
+ if not isinstance(key, str):
194
+ raise ChunkIdentityError("identity mapping keys must be strings")
195
+ normalized_key = normalize_identity_text(key)
196
+ if normalized_key in normalized:
197
+ raise ChunkIdentityError(
198
+ "identity mapping keys must remain unique after normalization"
199
+ )
200
+ normalized[normalized_key] = _normalize_value(item, active_containers)
201
+ return normalized
202
+ if isinstance(value, (list, tuple)):
203
+ if id(value) in active_containers:
204
+ raise ChunkIdentityError("identity input must not contain cycles")
205
+ active_containers = active_containers | {id(value)}
206
+ return [_normalize_value(item, active_containers) for item in value]
207
+ if value is None or isinstance(value, (bool, int, float)):
208
+ return value
209
+ raise ChunkIdentityError(f"identity input type is not supported: {type(value).__name__}")
@@ -0,0 +1,61 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Iterator, Mapping
4
+ from math import isfinite
5
+ from typing import Annotated, Any
6
+
7
+ from pydantic import AfterValidator, PlainSerializer
8
+
9
+
10
+ def _freeze_metadata_value(value: Any) -> Any:
11
+ if isinstance(value, Mapping):
12
+ return FrozenMetadata(value)
13
+ if isinstance(value, (list, tuple)):
14
+ return tuple(_freeze_metadata_value(item) for item in value)
15
+ if value is None or isinstance(value, (str, int, bool)):
16
+ return value
17
+ if isinstance(value, float):
18
+ if not isfinite(value):
19
+ raise ValueError("chunk metadata numbers must be finite")
20
+ return value
21
+ raise ValueError(f"chunk metadata values must be JSON-compatible, got {type(value).__name__}")
22
+
23
+
24
+ class FrozenMetadata(Mapping[str, Any]):
25
+ """Recursively immutable provider metadata with JSON-compatible serialization."""
26
+
27
+ __slots__ = ("_values",)
28
+
29
+ def __init__(self, values: Mapping[str, Any] | None = None) -> None:
30
+ self._values = {
31
+ str(key): _freeze_metadata_value(value) for key, value in (values or {}).items()
32
+ }
33
+
34
+ def __getitem__(self, key: str) -> Any:
35
+ return self._values[key]
36
+
37
+ def __iter__(self) -> Iterator[str]:
38
+ return iter(self._values)
39
+
40
+ def __len__(self) -> int:
41
+ return len(self._values)
42
+
43
+ def __repr__(self) -> str:
44
+ return f"FrozenMetadata({self._values!r})"
45
+
46
+
47
+ def thaw_metadata(value: Any) -> Any:
48
+ """Return ordinary JSON containers from recursively frozen metadata."""
49
+
50
+ if isinstance(value, Mapping):
51
+ return {str(key): thaw_metadata(item) for key, item in value.items()}
52
+ if isinstance(value, tuple):
53
+ return [thaw_metadata(item) for item in value]
54
+ return value
55
+
56
+
57
+ ChunkMetadata = Annotated[
58
+ Mapping[str, Any],
59
+ AfterValidator(FrozenMetadata),
60
+ PlainSerializer(thaw_metadata, return_type=dict[str, Any]),
61
+ ]
@@ -0,0 +1,164 @@
1
+ """The canonical chunk record every projection is rebuilt from.
2
+
3
+ A record is immutable. Values derived from it, such as ``chunk_kinds``, are
4
+ computed on read and never stored beside the fields they come from.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pydantic import Field, model_validator
10
+
11
+ from harborrag_core.base import StrictModel
12
+ from harborrag_core.schemas.ids import ChunkId, DocumentId, DocumentVersionId, TenantId
13
+
14
+ from .metadata import ChunkMetadata, FrozenMetadata
15
+ from .schemas import (
16
+ ChunkHierarchy,
17
+ ChunkKind,
18
+ ChunkQuality,
19
+ ChunkRelation,
20
+ ConnectorType,
21
+ DocumentKind,
22
+ RecordKind,
23
+ )
24
+ from .source_schemas import ChunkSecurity, CitationLocator, SourceAttribute
25
+ from .table_schemas import TableChunkLocator
26
+
27
+ _CODE_FENCES = frozenset({"```", "~~~"})
28
+ """Markers that open and close a fenced code block in Markdown."""
29
+
30
+
31
+ class ChunkRecord(StrictModel):
32
+ """Canonical immutable, source-independent chunk revision."""
33
+
34
+ schema_version: str = Field(default="1.0", min_length=1)
35
+ strategy_version: str = Field(min_length=1)
36
+ chunk_id: ChunkId
37
+ logical_chunk_id: ChunkId
38
+ content_hash: str = Field(min_length=1)
39
+
40
+ connector_type: ConnectorType
41
+ document_kind: DocumentKind
42
+ record_kind: RecordKind
43
+ chunk_kind: ChunkKind
44
+
45
+ tenant_id: TenantId
46
+ connection_id: str = Field(min_length=1)
47
+ source_scope_id: str = Field(min_length=1)
48
+ source_item_id: str = Field(min_length=1)
49
+ source_version: str = Field(min_length=1)
50
+ document_id: DocumentId
51
+ document_version_id: DocumentVersionId
52
+ ordinal: int = Field(ge=0)
53
+
54
+ content: str
55
+ embedding_text: str = Field(min_length=1)
56
+ search_text: str = Field(min_length=1)
57
+ token_count: int = Field(ge=0)
58
+ language: str | None = None
59
+
60
+ citation_locator: CitationLocator = Field(default_factory=CitationLocator)
61
+ hierarchy: ChunkHierarchy = Field(default_factory=ChunkHierarchy)
62
+ security: ChunkSecurity
63
+ relations: tuple[ChunkRelation, ...] = ()
64
+ quality: ChunkQuality = Field(default_factory=ChunkQuality)
65
+ table_locator: TableChunkLocator | None = None
66
+ source_attributes: tuple[SourceAttribute, ...] = ()
67
+
68
+ metadata: ChunkMetadata = Field(default_factory=FrozenMetadata)
69
+
70
+ @property
71
+ def chunk_kinds(self) -> tuple[ChunkKind, ...]:
72
+ """Every kind of content the chunk holds, its own ``chunk_kind`` first.
73
+
74
+ A chunk whose content carries a Markdown table also lists ``table``, so a
75
+ table kept inside the text around it is still found as a table.
76
+ """
77
+ if self.chunk_kind != ChunkKind.TABLE and _holds_markdown_table(self.content):
78
+ return (self.chunk_kind, ChunkKind.TABLE)
79
+ return (self.chunk_kind,)
80
+
81
+ @model_validator(mode="after")
82
+ def validate_chunk(self) -> ChunkRecord:
83
+ """Check that the kind, text, locator and source fields agree."""
84
+ evidence_kinds = {
85
+ ChunkKind.TEXT,
86
+ ChunkKind.TABLE,
87
+ ChunkKind.CODE,
88
+ ChunkKind.COMMENT,
89
+ ChunkKind.EVENT,
90
+ ChunkKind.JIRA_FIELD,
91
+ }
92
+ if self.chunk_kind in evidence_kinds and not self.content.strip():
93
+ raise ValueError(f"content must be non-empty for {self.chunk_kind.value} chunks")
94
+ if not self.embedding_text.strip():
95
+ raise ValueError("embedding_text must be non-empty")
96
+ if not self.search_text.strip():
97
+ raise ValueError("search_text must be non-empty")
98
+ if self.chunk_kind == ChunkKind.TABLE and self.table_locator is None:
99
+ raise ValueError("table chunks require table_locator")
100
+ if self.chunk_kind != ChunkKind.TABLE and self.table_locator is not None:
101
+ raise ValueError("table_locator is only valid for table chunks")
102
+ if self.document_kind == DocumentKind.CONFLUENCE_PAGE and (
103
+ self.connector_type != ConnectorType.CONFLUENCE
104
+ ):
105
+ raise ValueError("confluence_page requires the confluence connector")
106
+ if self.document_kind == DocumentKind.JIRA_ISSUE and (
107
+ self.connector_type != ConnectorType.JIRA
108
+ ):
109
+ raise ValueError("jira_issue requires the jira connector")
110
+ if self.document_kind == DocumentKind.LOCAL_FILE and (
111
+ self.connector_type != ConnectorType.LOCAL
112
+ ):
113
+ raise ValueError("local_file requires the local connector")
114
+ self._validate_references()
115
+ self._validate_collections()
116
+ return self
117
+
118
+ def _validate_references(self) -> None:
119
+ own_ids = {str(self.chunk_id), str(self.logical_chunk_id)}
120
+ references = (
121
+ self.hierarchy.parent_chunk_id,
122
+ self.hierarchy.previous_chunk_id,
123
+ self.hierarchy.next_chunk_id,
124
+ )
125
+ if any(reference is not None and str(reference) in own_ids for reference in references):
126
+ raise ValueError("chunk hierarchy must not self-reference a chunk identity")
127
+ if any(relation.target_id in own_ids for relation in self.relations):
128
+ raise ValueError("chunk relations must not self-reference a chunk identity")
129
+
130
+ def _validate_collections(self) -> None:
131
+ relation_keys = {
132
+ (relation.relation_type, relation.target_id, relation.target_version_id)
133
+ for relation in self.relations
134
+ }
135
+ if len(relation_keys) != len(self.relations):
136
+ raise ValueError("chunk relations must not contain duplicates")
137
+ attribute_keys = {attribute.key for attribute in self.source_attributes}
138
+ if len(attribute_keys) != len(self.source_attributes):
139
+ raise ValueError("source_attributes keys must be unique")
140
+
141
+
142
+ def _holds_markdown_table(content: str) -> bool:
143
+ """Report whether two consecutive lines outside fenced code are table rows.
144
+
145
+ Two rows catch a header with its delimiter row, and also the rows of a table
146
+ whose header stayed in an earlier chunk. One pipe-bounded line alone is not
147
+ a table, and neither is a pipe-bounded example inside a code fence.
148
+ """
149
+ fence: str | None = None
150
+ previous_is_row = False
151
+ for line in content.splitlines():
152
+ stripped = line.strip()
153
+ marker = stripped[:3]
154
+ if marker in _CODE_FENCES and fence in {None, marker}:
155
+ fence = marker if fence is None else None
156
+ previous_is_row = False
157
+ continue
158
+ if fence is not None:
159
+ continue
160
+ is_row = len(stripped) > 1 and stripped.startswith("|") and stripped.endswith("|")
161
+ if is_row and previous_is_row:
162
+ return True
163
+ previous_is_row = is_row
164
+ return False