supaflow-python-sdk 1.0.74__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 (44) hide show
  1. supaflow_python_sdk/__init__.py +150 -0
  2. supaflow_python_sdk/_definition_validation.py +220 -0
  3. supaflow_python_sdk/_legacy_manifest.py +89 -0
  4. supaflow_python_sdk/_legacy_naming.py +50 -0
  5. supaflow_python_sdk/_precision_json.py +74 -0
  6. supaflow_python_sdk/base_connector.py +146 -0
  7. supaflow_python_sdk/capabilities.py +74 -0
  8. supaflow_python_sdk/catalog_naming.py +189 -0
  9. supaflow_python_sdk/child_settings.py +44 -0
  10. supaflow_python_sdk/compatibility.json +10 -0
  11. supaflow_python_sdk/connector_definition.py +279 -0
  12. supaflow_python_sdk/connector_fixture.py +13 -0
  13. supaflow_python_sdk/connector_identity.py +55 -0
  14. supaflow_python_sdk/connector_property.py +97 -0
  15. supaflow_python_sdk/connector_resource.py +388 -0
  16. supaflow_python_sdk/csv_record_emitter.py +288 -0
  17. supaflow_python_sdk/cursor_candidates.py +167 -0
  18. supaflow_python_sdk/errors.py +130 -0
  19. supaflow_python_sdk/field_capabilities.py +50 -0
  20. supaflow_python_sdk/helpers.py +98 -0
  21. supaflow_python_sdk/host_api.py +102 -0
  22. supaflow_python_sdk/job_context.py +39 -0
  23. supaflow_python_sdk/jsonl_record_emitter.py +727 -0
  24. supaflow_python_sdk/keyless_object_handling.py +19 -0
  25. supaflow_python_sdk/models.py +1052 -0
  26. supaflow_python_sdk/naming.py +267 -0
  27. supaflow_python_sdk/native_mapped_jsonl_record_emitter.py +180 -0
  28. supaflow_python_sdk/oauth.py +399 -0
  29. supaflow_python_sdk/openapi_schema_builder.py +778 -0
  30. supaflow_python_sdk/property_rules.py +27 -0
  31. supaflow_python_sdk/py.typed +0 -0
  32. supaflow_python_sdk/resource_options.py +9 -0
  33. supaflow_python_sdk/schema_compliance.py +481 -0
  34. supaflow_python_sdk/source.py +165 -0
  35. supaflow_python_sdk/source_namespace.py +325 -0
  36. supaflow_python_sdk/supa_id.py +422 -0
  37. supaflow_python_sdk/temporal_stage_value.py +136 -0
  38. supaflow_python_sdk/type_inference.py +583 -0
  39. supaflow_python_sdk/ui.py +45 -0
  40. supaflow_python_sdk/write_plan.py +112 -0
  41. supaflow_python_sdk-1.0.74.dist-info/METADATA +80 -0
  42. supaflow_python_sdk-1.0.74.dist-info/RECORD +44 -0
  43. supaflow_python_sdk-1.0.74.dist-info/WHEEL +5 -0
  44. supaflow_python_sdk-1.0.74.dist-info/top_level.txt +1 -0
@@ -0,0 +1,422 @@
1
+ """Double-SHA-256 _supa_id computation.
2
+
3
+ Shared framework module used by:
4
+ - S3 destination connector (imports via supaflow_connector_s3.supa_id re-export)
5
+ - DeclarativeDltConnector emit path (imports directly)
6
+
7
+ Algorithm mirrors Java S3Writer.generateSupaId() / SnowflakeLoader.computeSupaId()
8
+ and the historical supaflow_connector_s3/supa_id.py:
9
+ 1. Select hash fields (PK > Unique > all selected).
10
+ 2. For each field, normalize value for its canonical type and SHA-256 it.
11
+ 3. Join per-field digests with '|' and SHA-256 the result.
12
+
13
+ Input-shape agnostic: core helpers operate on list[HashField]. Callers convert
14
+ from their native shape (Java bridge dicts, SDK MetadataField dataclasses) via
15
+ the adapter functions below.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import logging
21
+ import os
22
+ import uuid
23
+ from .keyless_object_handling import KeylessObjectHandling
24
+
25
+ from dataclasses import dataclass
26
+ from datetime import datetime, date, timezone
27
+ from typing import Any, Iterable
28
+
29
+ _log = logging.getLogger(__name__)
30
+
31
+
32
+ def supa_id_debug_enabled() -> bool:
33
+ """Gate for the structured _supa_id input/output logging.
34
+
35
+ Set ``SUPAFLOW_DEBUG_SUPA_ID=true`` to emit one INFO line per
36
+ _supa_id computation that captures every input the hash depends on.
37
+ Off by default -- production logs stay clean. Use this when an
38
+ instability is observed (different _supa_id for the same business
39
+ content across runs) and the divergence point isn't obvious from
40
+ static analysis. Two runs with logging enabled, then a per-row diff
41
+ of the logged inputs, surfaces the varying field immediately.
42
+
43
+ Reads the env var on every call so the toggle can be flipped during
44
+ a long-running pipeline without restarting the process. The
45
+ branch is taken on a hot path; the lookup is cheap (~0.3us) and
46
+ only the formatted log payload is built when enabled.
47
+ """
48
+ return os.environ.get("SUPAFLOW_DEBUG_SUPA_ID", "").strip().lower() in (
49
+ "1", "true", "yes", "on",
50
+ )
51
+
52
+
53
+ def _supa_id_debug_enabled() -> bool:
54
+ """Backward-compatible internal alias for existing callers."""
55
+ return supa_id_debug_enabled()
56
+
57
+
58
+ def _log_supa_id_inputs(
59
+ *,
60
+ kind: str,
61
+ table_name: str | None,
62
+ parent_supa_id: str | None,
63
+ list_idx: int | None,
64
+ pk_field_names: list[str] | None,
65
+ pk_field_canonical_types: list[str] | None,
66
+ pk_field_values: list[Any] | None,
67
+ pk_field_normalized: list[str] | None,
68
+ content_field_names: list[str] | None = None,
69
+ content_normalized: list[str] | None = None,
70
+ content_hash: str | None = None,
71
+ pk_hash: str | None = None,
72
+ result: str = "",
73
+ ) -> None:
74
+ """Emit one INFO line capturing all hash inputs for diagnostics.
75
+
76
+ The format is line-based key=value pairs so that a `grep | awk`
77
+ pipeline can extract specific fields from a job log. Multi-value
78
+ fields (per-PK lists) are rendered as ``;``-separated strings to
79
+ survive log aggregation that splits on commas. Values that may
80
+ contain ``;`` or newlines are passed through ``repr()`` so the line
81
+ stays single-line and parseable.
82
+ """
83
+ def _join(seq: list[Any] | None) -> str:
84
+ if seq is None:
85
+ return ""
86
+ return ";".join(repr(v) for v in seq)
87
+ _log.info(
88
+ "[supa-id-debug] kind=%s table=%s parent=%s list_idx=%s "
89
+ "pk_names=%s pk_types=%s pk_values=%s pk_normalized=%s "
90
+ "content_names=%s content_normalized=%s content_hash=%s "
91
+ "pk_hash=%s result=%s",
92
+ kind,
93
+ table_name or "",
94
+ parent_supa_id or "",
95
+ list_idx if list_idx is not None else "",
96
+ _join(pk_field_names),
97
+ _join(pk_field_canonical_types),
98
+ _join(pk_field_values),
99
+ _join(pk_field_normalized),
100
+ _join(content_field_names),
101
+ _join(content_normalized),
102
+ content_hash or "",
103
+ pk_hash or "",
104
+ result,
105
+ )
106
+
107
+
108
+ # Columns added by Supaflow itself. Only the ALL_FIELDS fallback excludes these
109
+ # to avoid circular self-reference when no explicit key is declared. Explicit
110
+ # PK/Unique paths keep _supa_id so the passthrough rule can fire.
111
+ #
112
+ # Cross-language parity: the Java side mirrors this in
113
+ # io.supaflow.core.util.SupaflowInternalNames.SUPA_SYSTEM_COLUMNS. Keep in sync.
114
+ SUPA_SYSTEM_COLUMNS = frozenset({
115
+ "_supa_synced", "_supa_deleted", "_supa_index", "_supa_id", "_supa_job_id",
116
+ })
117
+
118
+
119
+ @dataclass(frozen=True)
120
+ class HashField:
121
+ """Minimal field descriptor consumed by the hash helpers.
122
+
123
+ Adapters in this module convert from Java bridge dicts (camelCase) and
124
+ SDK MetadataField dataclasses (snake_case) into this uniform shape.
125
+
126
+ ``selected`` preserves the S3 ALL_FIELDS behavior: the fallback path
127
+ only hashes user-selected business fields. Adapters default it to True
128
+ when the source has no notion of selection (e.g. pure HashField-based
129
+ callers), matching the historical dict semantics.
130
+ """
131
+ name: str
132
+ canonical_type: str = "STRING"
133
+ primary_key: bool = False
134
+ unique: bool = False
135
+ selected: bool = True
136
+
137
+
138
+ def _sha256_hex(text: str) -> str:
139
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
140
+
141
+
142
+ def normalize_for_hash(value: Any, canonical_type: str) -> str:
143
+ """Normalize a value to a canonical string for SHA-256 hashing.
144
+
145
+ Types supported: STRING, BOOLEAN, LOCALDATE, LOCALDATETIME, INSTANT.
146
+ All other canonical types fall through to ``str(value)``.
147
+ """
148
+ if value is None or (isinstance(value, str) and value == "\\N"):
149
+ return ""
150
+ ct = (canonical_type or "STRING").upper()
151
+ if ct == "BOOLEAN":
152
+ if isinstance(value, bool):
153
+ return str(value).lower()
154
+ return str(value).strip().lower()
155
+ if ct == "LOCALDATE":
156
+ if isinstance(value, (datetime, date)):
157
+ d = value.date() if isinstance(value, datetime) else value
158
+ return d.strftime("%Y-%m-%d")
159
+ return str(value)
160
+ if ct == "LOCALDATETIME":
161
+ if isinstance(value, datetime):
162
+ return value.strftime("%Y-%m-%dT%H:%M:%S.%f")
163
+ return str(value)
164
+ if ct == "INSTANT":
165
+ if isinstance(value, datetime):
166
+ if value.tzinfo is None:
167
+ value = value.replace(tzinfo=timezone.utc)
168
+ utc = value.astimezone(timezone.utc)
169
+ return utc.strftime("%Y-%m-%dT%H:%M:%S.%f") + " +00:00"
170
+ return str(value)
171
+ return str(value)
172
+
173
+
174
+ def resolve_supa_id_strategy(
175
+ fields: list[HashField],
176
+ load_mode: str | None = None,
177
+ *,
178
+ keyless_object_handling: KeylessObjectHandling | str | None = None,
179
+ ) -> dict:
180
+ """Resolve which fields go into the _supa_id hash.
181
+
182
+ Priority: PK > Unique > pipeline keyless policy (UUID by default).
183
+ load_mode is retained for callers but never determines identity.
184
+ ``HashField.primary_key`` is expected to mean the orchestrator's effective
185
+ business key: user selection first, connector ``source_primary_key`` default
186
+ second. This is why the PK path is higher priority than connector-local
187
+ defaults and uniqueness hints.
188
+
189
+ When the explicit key is the sole _supa_id, returns PASSTHROUGH so the
190
+ existing value flows through unchanged. That pass-through is for sources
191
+ that already provide a Supaflow-managed pseudokey; discovery/selection
192
+ metadata should still not stamp generated ``_supa_id`` as a source or
193
+ effective business primary key.
194
+ """
195
+ policy = KeylessObjectHandling.parse(keyless_object_handling)
196
+
197
+ def _is_sole_supa_id(fs: list[HashField]) -> bool:
198
+ return len(fs) == 1 and fs[0].name.lower() == "_supa_id"
199
+
200
+ pk_fields = [f for f in fields if f.primary_key]
201
+ if pk_fields:
202
+ if _is_sole_supa_id(pk_fields):
203
+ return {"strategy": "PASSTHROUGH", "fields": pk_fields}
204
+ return {"strategy": "PK", "fields": pk_fields}
205
+
206
+ unique_fields = [f for f in fields if f.unique]
207
+ if unique_fields:
208
+ if _is_sole_supa_id(unique_fields):
209
+ return {"strategy": "PASSTHROUGH", "fields": unique_fields}
210
+ return {"strategy": "UNIQUE", "fields": unique_fields}
211
+
212
+ if policy == KeylessObjectHandling.UUID:
213
+ return {"strategy": "UUID_V4", "fields": []}
214
+
215
+ # ALL_FIELDS path: user-selected only, excluding _supa_* to avoid
216
+ # circular self-reference. Matches the historical S3 behavior where
217
+ # unselected fields are dropped from the hash even in the fallback.
218
+ all_fields = [
219
+ f for f in fields
220
+ if f.selected and f.name.lower() not in SUPA_SYSTEM_COLUMNS
221
+ ]
222
+ if all_fields:
223
+ return {"strategy": "ALL_FIELDS", "fields": all_fields}
224
+ return {"strategy": "NONE", "fields": []}
225
+
226
+
227
+ def select_hash_fields(
228
+ fields: list[HashField],
229
+ load_mode: str | None = None,
230
+ *,
231
+ keyless_object_handling: KeylessObjectHandling | str | None = None,
232
+ ) -> list[HashField]:
233
+ """Return the field subset that feeds the hash (empty for PASSTHROUGH/UUID)."""
234
+ return resolve_supa_id_strategy(fields, load_mode, keyless_object_handling=keyless_object_handling).get("fields", [])
235
+
236
+
237
+ def compute_supa_id(
238
+ record: dict,
239
+ fields: list[HashField],
240
+ load_mode: str | None = None,
241
+ *,
242
+ keyless_object_handling: KeylessObjectHandling | str | None = None,
243
+ ) -> str:
244
+ """Compute _supa_id for a single record.
245
+
246
+ PASSTHROUGH: return the existing _supa_id value verbatim.
247
+ UUID_V4: fresh uuid4().hex (UUID policy + no explicit key).
248
+ Otherwise: sha256( '|'.join( sha256(normalize_for_hash(val, ct)) ... ) ).
249
+ """
250
+ strategy = resolve_supa_id_strategy(fields, load_mode, keyless_object_handling=keyless_object_handling)
251
+ hash_fields = strategy["fields"]
252
+
253
+ if strategy["strategy"] == "PASSTHROUGH":
254
+ val = record.get("_supa_id")
255
+ return str(val) if val is not None else ""
256
+ if strategy["strategy"] == "UUID_V4":
257
+ return uuid.uuid4().hex
258
+
259
+ debug_enabled = _supa_id_debug_enabled()
260
+ per_field_digests = []
261
+ raw_values: list[Any] | None = [] if debug_enabled else None
262
+ normalized_values: list[str] | None = [] if debug_enabled else None
263
+ for f in hash_fields:
264
+ raw = record.get(f.name)
265
+ normalised = normalize_for_hash(raw, f.canonical_type)
266
+ per_field_digests.append(_sha256_hex(normalised))
267
+ if debug_enabled:
268
+ raw_values.append(raw)
269
+ normalized_values.append(normalised)
270
+ result = _sha256_hex("|".join(per_field_digests))
271
+ if debug_enabled:
272
+ _log_supa_id_inputs(
273
+ kind="root",
274
+ table_name=None,
275
+ parent_supa_id=None,
276
+ list_idx=None,
277
+ pk_field_names=[f.name for f in hash_fields],
278
+ pk_field_canonical_types=[f.canonical_type for f in hash_fields],
279
+ pk_field_values=raw_values,
280
+ pk_field_normalized=normalized_values,
281
+ result=result,
282
+ )
283
+ return result
284
+
285
+
286
+ def compute_child_supa_id_with_pk(
287
+ parent_supa_id: str,
288
+ child_record: dict,
289
+ pk_fields: list[HashField],
290
+ *,
291
+ table_name: str | None = None,
292
+ ) -> str:
293
+ """Case A: child row has a business PK (e.g., Jira component id).
294
+
295
+ Hash = sha256( parent_supa_id + '|' + sha256(child_pk_values_joined) ).
296
+ Entity-stable: reordering the parent's array does not change the child hash.
297
+
298
+ ``pk_fields`` carries the real canonical types for each PK column. Using
299
+ the type is critical: a LONG PK must normalize to the digit string, a
300
+ BOOLEAN to "true"/"false", an INSTANT to the UTC-rendered timestamp, etc.
301
+ Hardcoding STRING would diverge from the destination-side hash the spec
302
+ promises to match.
303
+ """
304
+ debug_enabled = _supa_id_debug_enabled()
305
+ per_field_digests = []
306
+ raw_values: list[Any] | None = [] if debug_enabled else None
307
+ normalized_values: list[str] | None = [] if debug_enabled else None
308
+ for f in pk_fields:
309
+ raw = child_record.get(f.name)
310
+ normalised = normalize_for_hash(raw, f.canonical_type)
311
+ per_field_digests.append(_sha256_hex(normalised))
312
+ if debug_enabled:
313
+ raw_values.append(raw)
314
+ normalized_values.append(normalised)
315
+ pk_hash = _sha256_hex("|".join(per_field_digests))
316
+ result = _sha256_hex(parent_supa_id + "|" + pk_hash)
317
+ if debug_enabled:
318
+ _log_supa_id_inputs(
319
+ kind="child_case_a",
320
+ table_name=table_name,
321
+ parent_supa_id=parent_supa_id,
322
+ list_idx=None,
323
+ pk_field_names=[f.name for f in pk_fields],
324
+ pk_field_canonical_types=[f.canonical_type for f in pk_fields],
325
+ pk_field_values=raw_values,
326
+ pk_field_normalized=normalized_values,
327
+ pk_hash=pk_hash,
328
+ result=result,
329
+ )
330
+ return result
331
+
332
+
333
+ def compute_child_supa_id_with_position(
334
+ parent_supa_id: str,
335
+ list_idx: int,
336
+ child_record: dict,
337
+ child_fields: list[HashField],
338
+ *,
339
+ table_name: str | None = None,
340
+ ) -> str:
341
+ """Case B: child row is a bare-value array element (e.g., labels).
342
+
343
+ Hash = sha256( parent_supa_id + '|' + list_idx + '|' + content_hash )
344
+ where content_hash = sha256( '|'.join( sha256(normalize(field_i)) ) )
345
+ over all non-system business fields on the child row.
346
+
347
+ Position-stable: reordering the parent's array churns the hash (tradeoff
348
+ accepted; better than collisions on duplicate content).
349
+
350
+ Field order is normalized by name so the hash is stable against dict
351
+ iteration order from upstream JSON parsers and dlt serialization.
352
+ """
353
+ business = sorted(
354
+ (
355
+ f for f in child_fields
356
+ if f.name.lower() not in SUPA_SYSTEM_COLUMNS
357
+ and not f.name.startswith("_dlt_")
358
+ ),
359
+ key=lambda f: f.name,
360
+ )
361
+ debug_enabled = _supa_id_debug_enabled()
362
+ per_field_digests = []
363
+ normalized_values: list[str] | None = [] if debug_enabled else None
364
+ for f in business:
365
+ raw = child_record.get(f.name)
366
+ normalised = normalize_for_hash(raw, f.canonical_type)
367
+ per_field_digests.append(_sha256_hex(normalised))
368
+ if debug_enabled:
369
+ normalized_values.append(normalised)
370
+ content_hash = _sha256_hex("|".join(per_field_digests))
371
+ result = _sha256_hex(f"{parent_supa_id}|{list_idx}|{content_hash}")
372
+ if debug_enabled:
373
+ _log_supa_id_inputs(
374
+ kind="child_case_b",
375
+ table_name=table_name,
376
+ parent_supa_id=parent_supa_id,
377
+ list_idx=list_idx,
378
+ pk_field_names=None,
379
+ pk_field_canonical_types=None,
380
+ pk_field_values=None,
381
+ pk_field_normalized=None,
382
+ content_field_names=[f.name for f in business],
383
+ content_normalized=normalized_values,
384
+ content_hash=content_hash,
385
+ result=result,
386
+ )
387
+ return result
388
+
389
+
390
+ def _from_java_dict(d: dict) -> HashField:
391
+ """Adapt a Java-bridge field dict (camelCase keys) to a HashField.
392
+
393
+ ``selected`` defaults to True when absent -- matches the historical S3
394
+ behavior where ``f.get("selected", True)`` treated missing as included.
395
+ """
396
+ return HashField(
397
+ name=d.get("name", ""),
398
+ canonical_type=d.get("canonicalType", "STRING") or "STRING",
399
+ primary_key=bool(d.get("primaryKey") or d.get("isPrimaryKey")),
400
+ unique=bool(d.get("unique") or d.get("isUniqueKey")),
401
+ selected=bool(d.get("selected", True)),
402
+ )
403
+
404
+
405
+ def _from_metadata_field(mf) -> HashField:
406
+ """Adapt a supaflow_python_sdk.models.MetadataField to a HashField.
407
+
408
+ Both ``source_primary_key`` (discovery flag) and ``primary_key`` (user-
409
+ selection flag) count as PK for hash purposes. ``unique`` maps directly.
410
+ ``selected`` follows tri-state semantics: only False is treated as
411
+ deselected; True and None both count as selected (missing selection
412
+ info means fetch everything, same as the historical dict behavior).
413
+ """
414
+ raw_selected = getattr(mf, "selected", None)
415
+ return HashField(
416
+ name=mf.name,
417
+ canonical_type=mf.canonical_type or "STRING",
418
+ primary_key=bool(getattr(mf, "source_primary_key", None)
419
+ or getattr(mf, "primary_key", None)),
420
+ unique=bool(getattr(mf, "unique", None)),
421
+ selected=False if raw_selected is False else True,
422
+ )
@@ -0,0 +1,136 @@
1
+ """Destination-policy-aware encoding for typed staged temporal values."""
2
+ from __future__ import annotations
3
+
4
+ import datetime as _dt
5
+ import re
6
+ from typing import Any
7
+
8
+
9
+ _ISO_DATETIME = re.compile(
10
+ r"^(?P<date>\d{4}-\d{2}-\d{2})[T ]"
11
+ r"(?P<time>\d{2}:\d{2}:\d{2})"
12
+ r"(?:\.(?P<fraction>\d{1,9}))?"
13
+ r"(?P<offset>Z|[+-]\d{2}:\d{2})?$"
14
+ )
15
+
16
+
17
+ def validate_max_fractional_second_digits(value: int | None) -> None:
18
+ if value is not None and (
19
+ isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 9
20
+ ):
21
+ raise ValueError(
22
+ "max_fractional_second_digits must be an integer between 0 and 9, got "
23
+ f"{value!r}"
24
+ )
25
+
26
+
27
+ def encode_temporal_stage_value(
28
+ value: Any,
29
+ target_type: Any,
30
+ max_fractional_second_digits: int | None,
31
+ ) -> Any:
32
+ """Encode one typed temporal value, preserving legacy values when unset.
33
+
34
+ Declared policies floor-truncate fractional seconds without rounding.
35
+ Unparseable values are returned unchanged so the destination loader remains
36
+ the fail-loud validation point.
37
+ """
38
+ validate_max_fractional_second_digits(max_fractional_second_digits)
39
+ if value is None or target_type is None or max_fractional_second_digits is None:
40
+ return value
41
+
42
+ canonical_type = getattr(target_type, "value", target_type)
43
+ canonical_type = str(canonical_type).upper()
44
+ try:
45
+ if canonical_type == "LOCALDATE":
46
+ return _local_date(value)
47
+ if canonical_type == "LOCALDATETIME":
48
+ return _local_datetime(value, max_fractional_second_digits)
49
+ if canonical_type == "INSTANT":
50
+ return _instant(value, max_fractional_second_digits)
51
+ except (TypeError, ValueError, OverflowError):
52
+ return value
53
+ return value
54
+
55
+
56
+ def _local_date(value: Any) -> Any:
57
+ if isinstance(value, _dt.datetime):
58
+ return value.date().isoformat()
59
+ if isinstance(value, _dt.date):
60
+ return value.isoformat()
61
+ if isinstance(value, str):
62
+ return _dt.date.fromisoformat(value).isoformat()
63
+ return value
64
+
65
+
66
+ def _local_datetime(value: Any, digits: int) -> Any:
67
+ if isinstance(value, _dt.datetime):
68
+ local = value.replace(tzinfo=None)
69
+ return _format_native_datetime(local, digits, utc=False)
70
+ if isinstance(value, str):
71
+ match = _ISO_DATETIME.fullmatch(value)
72
+ if match is None:
73
+ return value
74
+ # Validate calendar/time components without routing the fraction through
75
+ # Python datetime, whose microsecond ceiling would discard digits 7-9.
76
+ _dt.datetime.fromisoformat(f"{match['date']}T{match['time']}")
77
+ return _format_parts(
78
+ match["date"], match["time"], match["fraction"] or "", digits, ""
79
+ )
80
+ return value
81
+
82
+
83
+ def _instant(value: Any, digits: int) -> Any:
84
+ if isinstance(value, _dt.datetime):
85
+ instant = value
86
+ if instant.tzinfo is None:
87
+ instant = instant.replace(tzinfo=_dt.timezone.utc)
88
+ return _format_native_datetime(
89
+ instant.astimezone(_dt.timezone.utc), digits, utc=True
90
+ )
91
+ if isinstance(value, str):
92
+ match = _ISO_DATETIME.fullmatch(value)
93
+ if match is None:
94
+ return value
95
+ offset = match["offset"]
96
+ base = f"{match['date']}T{match['time']}"
97
+ if offset == "Z":
98
+ parsed = _dt.datetime.fromisoformat(base + "+00:00")
99
+ elif offset:
100
+ parsed = _dt.datetime.fromisoformat(base + offset)
101
+ else:
102
+ parsed = _dt.datetime.fromisoformat(base).replace(
103
+ tzinfo=_dt.timezone.utc
104
+ )
105
+ utc = parsed.astimezone(_dt.timezone.utc)
106
+ return _format_parts(
107
+ utc.date().isoformat(),
108
+ utc.time().replace(tzinfo=None).isoformat(timespec="seconds"),
109
+ match["fraction"] or "",
110
+ digits,
111
+ "Z",
112
+ )
113
+ return value
114
+
115
+
116
+ def _format_native_datetime(value: _dt.datetime, digits: int, *, utc: bool) -> str:
117
+ fraction = f"{value.microsecond:06d}" if value.microsecond else ""
118
+ return _format_parts(
119
+ value.date().isoformat(),
120
+ value.time().replace(tzinfo=None).isoformat(timespec="seconds"),
121
+ fraction,
122
+ digits,
123
+ "Z" if utc else "",
124
+ )
125
+
126
+
127
+ def _format_parts(
128
+ date: str,
129
+ time: str,
130
+ fraction: str,
131
+ digits: int,
132
+ suffix: str,
133
+ ) -> str:
134
+ truncated = fraction[:digits].rstrip("0")
135
+ fractional = f".{truncated}" if truncated else ""
136
+ return f"{date}T{time}{fractional}{suffix}"