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,727 @@
1
+ """JSONL chunk emitter for the mapped JSONL lane.
2
+
3
+ SDK-owned production transport. Connector authors use RecordEmitter;
4
+ this provides the JSONL transport for the JSONL-capable dlt destination path.
5
+
6
+ JSON encoding rules per MAPPED_RECORD_WRITE_PLAN_JSONL_SPEC.md L596-604.
7
+ Chunk rotation mirrors CsvRecordEmitter: byte-based, rotates before
8
+ writing a new record, file naming success_part_{n}.jsonl.gz. Records
9
+ stream directly into the active gzip part so memory scales with one encoded
10
+ record plus gzip/file buffers, not one full uncompressed chunk per emitter.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import atexit
15
+ import base64
16
+ import datetime as _dt
17
+ import decimal as _decimal
18
+ import hashlib
19
+ import json
20
+ import logging
21
+ import math
22
+ import os
23
+ import re
24
+ import struct
25
+ import uuid as _uuid
26
+ import weakref
27
+ import zlib
28
+ from typing import Any
29
+
30
+ from supaflow_python_sdk import _precision_json
31
+ from supaflow_python_sdk.supa_id import SUPA_SYSTEM_COLUMNS, supa_id_debug_enabled
32
+ from supaflow_python_sdk.source import RecordEmitResult
33
+ from supaflow_python_sdk.write_plan import RecordWritePlan, SupaflowSystemField
34
+ from supaflow_python_sdk.temporal_stage_value import (
35
+ encode_temporal_stage_value,
36
+ validate_max_fractional_second_digits,
37
+ )
38
+
39
+ # Retain the existing diagnostic category during the ownership migration.
40
+ _log = logging.getLogger("supaflow_python_runtime.jsonl_record_emitter")
41
+
42
+
43
+ def _is_legacy_null_marker(value: Any) -> bool:
44
+ return isinstance(value, str) and value == "\\N"
45
+
46
+
47
+ def _json_value(value: Any, *, legacy_null_marker_as_null: bool = False) -> Any:
48
+ """Apply per-spec encoding rules to a single value.
49
+
50
+ Rule ordering matters:
51
+ - None returns immediately as None (JSON null).
52
+ - bool MUST be checked before int because bool is a subclass of int;
53
+ without this guard, True/False would fall into the numeric branch.
54
+ - int and float pass through as JSON numbers.
55
+ - dict and list recurse so payload-level legacy null handling is uniform.
56
+ - bytes/bytearray/memoryview are base64-encoded to ASCII strings.
57
+ - datetime.datetime MUST be checked before datetime.date because
58
+ datetime.datetime subclasses datetime.date; the same ordering rule
59
+ that applies to bool/int applies here.
60
+ - str passes through as-is.
61
+ - Everything else falls back to str(value).
62
+ """
63
+ if value is None:
64
+ return None
65
+ if legacy_null_marker_as_null and _is_legacy_null_marker(value):
66
+ return None
67
+ if isinstance(value, bool):
68
+ return value
69
+ if isinstance(value, (int, float, _precision_json.JsonNumber)):
70
+ return value
71
+ if isinstance(value, dict):
72
+ return {
73
+ str(key): _json_value(
74
+ item,
75
+ legacy_null_marker_as_null=legacy_null_marker_as_null,
76
+ )
77
+ for key, item in value.items()
78
+ }
79
+ if isinstance(value, (list, tuple)):
80
+ return [
81
+ _json_value(
82
+ item,
83
+ legacy_null_marker_as_null=legacy_null_marker_as_null,
84
+ )
85
+ for item in value
86
+ ]
87
+ if isinstance(value, (bytes, bytearray, memoryview)):
88
+ return base64.b64encode(bytes(value)).decode("ascii")
89
+ if isinstance(value, (_dt.datetime, _dt.date, _dt.time)):
90
+ return value.isoformat()
91
+ if isinstance(value, str):
92
+ return value
93
+ return str(value)
94
+
95
+
96
+ _JSON_PARSE_MISS = object()
97
+ _OMIT_FIELD = object()
98
+ _JSON_NUMBER_RE = re.compile(r"-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?$")
99
+
100
+
101
+ def _field_attr(field: Any, snake_name: str, camel_name: str) -> Any:
102
+ if field is None:
103
+ return None
104
+ if isinstance(field, dict):
105
+ return field.get(snake_name) if snake_name in field else field.get(camel_name)
106
+ return getattr(field, snake_name, None)
107
+
108
+
109
+ def _binding_attr(binding: Any, snake_name: str, camel_name: str) -> Any:
110
+ if binding is None:
111
+ return None
112
+ if isinstance(binding, dict):
113
+ return binding.get(snake_name) if snake_name in binding else binding.get(camel_name)
114
+ return getattr(binding, snake_name, None)
115
+
116
+
117
+ def _is_empty_string_on_non_string_field(value: Any, field: Any) -> bool:
118
+ if field is None or not isinstance(value, str) or value != "":
119
+ return False
120
+ canonical_type = _field_attr(field, "canonical_type", "canonicalType")
121
+ # An empty base64 string represents zero bytes, not a missing binary value.
122
+ return str(canonical_type).upper() not in {"STRING", "BINARY"}
123
+
124
+
125
+ def _is_json_like_field(field: Any) -> bool:
126
+ if field is None:
127
+ return False
128
+ canonical_type = _field_attr(field, "canonical_type", "canonicalType")
129
+ if canonical_type is not None and str(canonical_type).upper() == "JSON":
130
+ return True
131
+ original_data_type = _field_attr(field, "original_data_type", "originalDataType")
132
+ if original_data_type is None:
133
+ return False
134
+ normalized = str(original_data_type).strip().upper()
135
+ return (
136
+ normalized.startswith("JSON")
137
+ or normalized.startswith("VARIANT")
138
+ or normalized.startswith("OBJECT")
139
+ or normalized.startswith("ARRAY")
140
+ )
141
+
142
+
143
+ def _is_json_payload_binding(binding: Any) -> bool:
144
+ return _is_json_like_field(_binding_attr(binding, "target_field", "targetField"))
145
+
146
+
147
+ def _is_string_field(field: Any) -> bool:
148
+ canonical_type = _field_attr(field, "canonical_type", "canonicalType")
149
+ return canonical_type is not None and str(canonical_type).upper() == "STRING"
150
+
151
+
152
+ def _is_structured_json_value(value: Any) -> bool:
153
+ return isinstance(value, (dict, list, tuple))
154
+
155
+
156
+ def _is_supported_json_string_value(value: Any) -> bool:
157
+ return (
158
+ value is None
159
+ or isinstance(
160
+ value,
161
+ (
162
+ str,
163
+ bool,
164
+ int,
165
+ float,
166
+ _decimal.Decimal,
167
+ bytes,
168
+ bytearray,
169
+ memoryview,
170
+ _dt.datetime,
171
+ _dt.date,
172
+ _dt.time,
173
+ _dt.timedelta,
174
+ _uuid.UUID,
175
+ ),
176
+ )
177
+ or _is_structured_json_value(value)
178
+ )
179
+
180
+
181
+ def _binding_field_name(binding: Any) -> str:
182
+ name = _binding_attr(binding, "source_name", "sourceName")
183
+ return str(name) if name else "<unknown>"
184
+
185
+
186
+ def _reject_unordered_json_values(value: Any, field_name: str) -> None:
187
+ if isinstance(value, (set, frozenset)):
188
+ raise ValueError(
189
+ f"Cannot encode field '{field_name}' as deterministic JSON text: "
190
+ f"unordered {type(value).__name__} values are not valid deterministic JSON"
191
+ )
192
+ if isinstance(value, dict):
193
+ for item in value.values():
194
+ _reject_unordered_json_values(item, field_name)
195
+ elif isinstance(value, (list, tuple)):
196
+ for item in value:
197
+ _reject_unordered_json_values(item, field_name)
198
+
199
+
200
+ def _canonical_float_text(value: float, field_name: str) -> str:
201
+ if not math.isfinite(value):
202
+ raise ValueError(
203
+ f"Cannot encode field '{field_name}' as deterministic JSON text: "
204
+ "non-finite floating-point values are not valid JSON"
205
+ )
206
+ if value == 0.0:
207
+ return "0"
208
+ return format(_decimal.Decimal(repr(value)).normalize(), "f")
209
+
210
+
211
+ def _trim_fractional_seconds(encoded: str) -> str:
212
+ decimal_point = encoded.find(".")
213
+ if decimal_point < 0:
214
+ return encoded
215
+
216
+ suffix_start = len(encoded)
217
+ for marker in ("Z", "+", "-"):
218
+ marker_index = encoded.find(marker, decimal_point + 1)
219
+ if marker_index >= 0:
220
+ suffix_start = min(suffix_start, marker_index)
221
+
222
+ fraction = encoded[decimal_point + 1:suffix_start].rstrip("0")
223
+ separator = "." if fraction else ""
224
+ return encoded[:decimal_point] + separator + fraction + encoded[suffix_start:]
225
+
226
+
227
+ def _canonical_temporal_text(value: Any) -> str:
228
+ if isinstance(value, _dt.datetime):
229
+ if value.tzinfo is not None:
230
+ utc = value.astimezone(_dt.timezone.utc).replace(tzinfo=None)
231
+ return _trim_fractional_seconds(utc.isoformat(timespec="auto") + "Z")
232
+ return _trim_fractional_seconds(value.isoformat(timespec="auto"))
233
+ if isinstance(value, _dt.time):
234
+ encoded = value.isoformat(timespec="auto")
235
+ if encoded.endswith("+00:00"):
236
+ encoded = encoded[:-6] + "Z"
237
+ return _trim_fractional_seconds(encoded)
238
+ return value.isoformat()
239
+
240
+
241
+ def _canonical_json_string(value: str) -> str:
242
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
243
+
244
+
245
+ def _canonical_json_object_key(key: Any) -> str:
246
+ if key is None:
247
+ return "null"
248
+ if isinstance(key, bool):
249
+ return "true" if key else "false"
250
+ return str(key)
251
+
252
+
253
+ def _canonical_json_text(value: Any, field_name: str) -> str:
254
+ _reject_unordered_json_values(value, field_name)
255
+
256
+ def encode(item: Any) -> str:
257
+ if item is None:
258
+ return "null"
259
+ if isinstance(item, bool):
260
+ return "true" if item else "false"
261
+ if isinstance(item, str):
262
+ return _canonical_json_string(item)
263
+ if isinstance(item, int):
264
+ return str(item)
265
+ if isinstance(item, float):
266
+ return _canonical_float_text(item, field_name)
267
+ if isinstance(item, _precision_json.JsonNumber):
268
+ return str(item)
269
+ if isinstance(item, _decimal.Decimal):
270
+ return _canonical_json_string(str(item))
271
+ if isinstance(item, (bytes, bytearray, memoryview)):
272
+ return _canonical_json_string(
273
+ base64.b64encode(bytes(item)).decode("ascii")
274
+ )
275
+ if isinstance(item, (_dt.datetime, _dt.date, _dt.time)):
276
+ return _canonical_json_string(_canonical_temporal_text(item))
277
+ if isinstance(item, _dt.timedelta):
278
+ return _canonical_float_text(item.total_seconds(), field_name)
279
+ if isinstance(item, _uuid.UUID):
280
+ return _canonical_json_string(str(item))
281
+ if isinstance(item, dict):
282
+ return "{" + ",".join(
283
+ _canonical_json_string(_canonical_json_object_key(key))
284
+ + ":"
285
+ + encode(child)
286
+ for key, child in item.items()
287
+ ) + "}"
288
+ if isinstance(item, (list, tuple)):
289
+ return "[" + ",".join(encode(child) for child in item) + "]"
290
+ raise ValueError(
291
+ f"Cannot encode field '{field_name}' as deterministic JSON text: "
292
+ f"runtime type {type(item).__module__}.{type(item).__qualname__} "
293
+ "is outside the JSON STRING allowlist"
294
+ )
295
+
296
+ return encode(value)
297
+
298
+
299
+ def _should_stringify_for_string_target(value: Any, binding: Any) -> bool:
300
+ return (
301
+ _is_string_field(_binding_attr(binding, "target_field", "targetField"))
302
+ and (
303
+ _is_structured_json_value(value)
304
+ or (
305
+ _is_json_like_field(
306
+ _binding_attr(binding, "source_field", "sourceField")
307
+ )
308
+ and _is_supported_json_string_value(value)
309
+ )
310
+ )
311
+ )
312
+
313
+
314
+ def _is_json_text_candidate(text: str) -> bool:
315
+ if not text:
316
+ return False
317
+ if text[0] in ('{', '[', '"'):
318
+ return True
319
+ if text in ("true", "false", "null"):
320
+ return True
321
+ return _JSON_NUMBER_RE.fullmatch(text) is not None
322
+
323
+
324
+ def _parse_json_text(value: Any) -> Any:
325
+ if not isinstance(value, str):
326
+ return _JSON_PARSE_MISS
327
+ text = value.strip()
328
+ if not _is_json_text_candidate(text):
329
+ return _JSON_PARSE_MISS
330
+ try:
331
+ return _precision_json.loads(text)
332
+ except Exception:
333
+ return _JSON_PARSE_MISS
334
+
335
+
336
+ def _json_payload_value(
337
+ value: Any,
338
+ binding: Any,
339
+ max_fractional_second_digits: int | None = None,
340
+ ) -> Any:
341
+ target_json_binding = _is_json_payload_binding(binding)
342
+ target_string_binding = _is_string_field(
343
+ _binding_attr(binding, "target_field", "targetField")
344
+ )
345
+ stringify_for_string_target = _should_stringify_for_string_target(value, binding)
346
+ field_name = _binding_field_name(binding)
347
+ if target_json_binding or target_string_binding:
348
+ _reject_unordered_json_values(value, field_name)
349
+ null_projection_field = (
350
+ _binding_attr(binding, "source_field", "sourceField")
351
+ or _binding_attr(binding, "target_field", "targetField")
352
+ )
353
+ if (target_json_binding or stringify_for_string_target) and (
354
+ value is None or _is_legacy_null_marker(value)
355
+ ):
356
+ return _OMIT_FIELD
357
+ if _is_empty_string_on_non_string_field(value, null_projection_field):
358
+ return _OMIT_FIELD if target_json_binding or stringify_for_string_target else None
359
+ if stringify_for_string_target:
360
+ if isinstance(value, str):
361
+ return value
362
+ return _canonical_json_text(value, field_name)
363
+ if target_json_binding:
364
+ parsed = _parse_json_text(value)
365
+ if parsed is not _JSON_PARSE_MISS:
366
+ return parsed
367
+ if max_fractional_second_digits is not None:
368
+ target_field = _binding_attr(binding, "target_field", "targetField")
369
+ target_type = _field_attr(target_field, "canonical_type", "canonicalType")
370
+ value = encode_temporal_stage_value(
371
+ value,
372
+ str(target_type).upper() if target_type is not None else None,
373
+ max_fractional_second_digits,
374
+ )
375
+ return _json_value(value, legacy_null_marker_as_null=True)
376
+
377
+
378
+ def _json_default_fallback(obj: Any) -> Any:
379
+ """Handle types that survive _json_value's fallback but json.dumps still rejects.
380
+
381
+ Mirrors csv_record_emitter._json_default for Decimal, UUID, timedelta,
382
+ and any remaining bytes-like types that arrive nested inside a dict/list
383
+ that was passed through by _json_value. Sets are rejected before this
384
+ fallback because they have no deterministic JSON order.
385
+ """
386
+ if isinstance(obj, (_dt.datetime, _dt.date, _dt.time)):
387
+ return obj.isoformat()
388
+ if isinstance(obj, _dt.timedelta):
389
+ return obj.total_seconds()
390
+ if isinstance(obj, _decimal.Decimal):
391
+ return str(obj)
392
+ if isinstance(obj, _uuid.UUID):
393
+ return str(obj)
394
+ if isinstance(obj, (bytes, bytearray, memoryview)):
395
+ return base64.b64encode(bytes(obj)).decode("ascii")
396
+ return str(obj)
397
+
398
+ # Minimum chunk size: 1 byte (no enforced minimum for JSONL -- callers use
399
+ # chunk_size=1 in tests to force per-record rotation).
400
+ _MIN_CHUNK_SIZE = 1
401
+ # Default chunk size: 64 MB. Chosen to match a common mid-size upload unit
402
+ # and give headroom below the 100 MB CsvRecordEmitter default so that mixed
403
+ # CSV+JSONL pipelines do not exhaust memory simultaneously.
404
+ _DEFAULT_CHUNK_SIZE = 64 * 1024 * 1024
405
+ _GZIP_HEADER = b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff"
406
+ _LIVE_EMITTERS: weakref.WeakSet["JsonlRecordEmitter"] = weakref.WeakSet()
407
+
408
+
409
+ def _close_live_emitters() -> None:
410
+ for emitter in list(_LIVE_EMITTERS):
411
+ try:
412
+ emitter.close()
413
+ except Exception:
414
+ pass
415
+
416
+
417
+ atexit.register(_close_live_emitters)
418
+
419
+
420
+ class JsonlRecordEmitter:
421
+ """Writes records as chunked JSONL matching the Java ChunkedOutputStream contract.
422
+
423
+ - Byte-based chunk rotation (not record-count)
424
+ - Rotation happens BEFORE writing a new record when current chunk would overflow
425
+ - File naming: success_part_{index}.jsonl.gz
426
+ - fsync on file and directory after each chunk
427
+ - close() is idempotent; emit() after close() raises RuntimeError
428
+ """
429
+
430
+ def __init__(
431
+ self,
432
+ *,
433
+ output_dir: str,
434
+ plan: RecordWritePlan,
435
+ chunk_size: int = _DEFAULT_CHUNK_SIZE,
436
+ ):
437
+ self._validate_plan(plan)
438
+ self._output_dir = output_dir
439
+ self._plan = plan
440
+ self._max_fractional_second_digits = plan.max_fractional_second_digits
441
+ validate_max_fractional_second_digits(self._max_fractional_second_digits)
442
+ self._chunk_size = max(chunk_size, _MIN_CHUNK_SIZE)
443
+ self._chunk_index = 0
444
+ self._current_part_uncompressed_bytes = 0
445
+ self._current_part_path: str | None = None
446
+ self._current_raw_file: Any | None = None
447
+ self._current_compressor: Any | None = None
448
+ self._current_crc = 0
449
+ self._closed = False
450
+ self._completed = False
451
+ self._records_emitted = 0
452
+ self._total_bytes_written = 0
453
+ self._debug_business_hasher = hashlib.sha256()
454
+ self._debug_supa_id_hasher = hashlib.sha256()
455
+ self._debug_first_samples: list[str] = []
456
+ _LIVE_EMITTERS.add(self)
457
+
458
+ @staticmethod
459
+ def _validate_plan(plan: RecordWritePlan) -> None:
460
+ """Validate write plan structure at construction time.
461
+
462
+ Checks:
463
+ 1. system_fields has exactly one binding per required system field (no missing,
464
+ no duplicates for the same SupaflowSystemField enum value). Using a Counter
465
+ on the field enum catches two bindings for the same field that have different
466
+ target_load_keys -- a case the previous set-equality check missed.
467
+ 2. No duplicate target_load_key across data fields + system fields under
468
+ case-insensitive comparison. Snowflake MATCH_BY_COLUMN_NAME = CASE_INSENSITIVE
469
+ collapses '_SUPA_ID' and '_supa_id' to the same column; an exact-string check
470
+ would miss that collision.
471
+ """
472
+ from collections import Counter
473
+
474
+ from supaflow_python_sdk.write_plan import SupaflowSystemField as _SF
475
+
476
+ counts = Counter(sb.field for sb in plan.system_fields)
477
+ missing = [f for f in _SF if counts.get(f, 0) == 0]
478
+ duplicates = [f for f, n in counts.items() if n > 1]
479
+ if missing or duplicates:
480
+ raise ValueError(
481
+ f"JsonlRecordEmitter: write plan must declare exactly one binding per "
482
+ f"required system field; missing={[f.column_name for f in missing]}, "
483
+ f"duplicates={[f.column_name for f in duplicates]}"
484
+ )
485
+
486
+ # Also reject extra bindings for field enum values outside SupaflowSystemField.
487
+ extra_names = [
488
+ sb.field.column_name for sb in plan.system_fields
489
+ if sb.field not in set(_SF)
490
+ ]
491
+ if extra_names:
492
+ raise ValueError(
493
+ f"JsonlRecordEmitter: write plan system_fields contains extra entries "
494
+ f"not in SUPA_SYSTEM_COLUMNS; extra={sorted(extra_names)}"
495
+ )
496
+
497
+ keys_normalized = (
498
+ [b.target_load_key.casefold() for b in plan.fields]
499
+ + [sb.target_load_key.casefold() for sb in plan.system_fields]
500
+ )
501
+ dupes = {k for k in keys_normalized if keys_normalized.count(k) > 1}
502
+ if dupes:
503
+ raise ValueError(
504
+ f"JsonlRecordEmitter: target_load_key collisions under case-insensitive "
505
+ f"matching: {sorted(dupes)}. Data and system load keys must be disjoint."
506
+ )
507
+
508
+ def emit(self, record: dict[str, Any]) -> None:
509
+ """Emit a single record as a JSONL line."""
510
+ if self._closed:
511
+ raise RuntimeError("Cannot emit: emitter is closed")
512
+
513
+ missing = [c for c in SUPA_SYSTEM_COLUMNS if c not in record]
514
+ if missing:
515
+ raise ValueError(
516
+ f"JsonlRecordEmitter: required system fields missing from record "
517
+ f"(will not emit partial row): {sorted(missing)}"
518
+ )
519
+
520
+ encoded = self._encode_record(record)
521
+ self._record_debug_fingerprint(record)
522
+
523
+ # Rotate before writing if adding this record would exceed chunk_size
524
+ # and the current part already has content. A single record larger
525
+ # than chunk_size is allowed and occupies its own oversized part.
526
+ if self._current_part_uncompressed_bytes and (
527
+ self._current_part_uncompressed_bytes + len(encoded) > self._chunk_size
528
+ ):
529
+ self._flush_chunk()
530
+
531
+ self._ensure_part_open()
532
+ compressed = self._current_compressor.compress(encoded)
533
+ if compressed:
534
+ self._current_raw_file.write(compressed)
535
+ self._current_crc = zlib.crc32(encoded, self._current_crc)
536
+ self._current_part_uncompressed_bytes += len(encoded)
537
+ self._records_emitted += 1
538
+
539
+ def complete(self) -> RecordEmitResult:
540
+ """Flush the remaining buffered data to disk and fsync.
541
+
542
+ Returns RecordEmitResult with records_emitted and bytes_written,
543
+ mirroring CsvRecordEmitter.complete() for lifecycle symmetry.
544
+ """
545
+ self._flush_chunk()
546
+ self._completed = True
547
+ if supa_id_debug_enabled():
548
+ _log.info(
549
+ "[supa-id-debug] kind=jsonl_output_fingerprint object=%s "
550
+ "output_dir=%s rows=%s bytes=%s business_rows_hash=%s "
551
+ "supa_id_list_hash=%s first_samples=%s",
552
+ self._debug_object_name(),
553
+ self._output_dir,
554
+ self._records_emitted,
555
+ self._total_bytes_written,
556
+ self._debug_business_hasher.hexdigest(),
557
+ self._debug_supa_id_hasher.hexdigest(),
558
+ ";".join(self._debug_first_samples),
559
+ )
560
+ return RecordEmitResult(
561
+ records_emitted=self._records_emitted,
562
+ bytes_written=self._total_bytes_written,
563
+ )
564
+
565
+ def close(self) -> None:
566
+ """Flush any pending bytes and mark the emitter closed.
567
+
568
+ Idempotent: calling twice does not raise. Flushes the pending
569
+ buffer on the first call so that callers who skip complete() still
570
+ get their bytes on disk (mirrors CsvRecordEmitter.close()).
571
+ """
572
+ if not self._closed:
573
+ self._flush_chunk()
574
+ self._closed = True
575
+ _LIVE_EMITTERS.discard(self)
576
+
577
+ def __del__(self):
578
+ try:
579
+ self.close()
580
+ except Exception:
581
+ pass
582
+
583
+ @property
584
+ def closed(self) -> bool:
585
+ return self._closed
586
+
587
+ @property
588
+ def output_dir(self) -> str:
589
+ """Public read-only access to the directory this emitter writes to."""
590
+ return self._output_dir
591
+
592
+ def _flush_chunk(self) -> None:
593
+ """Close the current part and fsync file + directory metadata."""
594
+ if self._current_compressor is None:
595
+ return
596
+
597
+ path = self._current_part_path
598
+ raw_file = self._current_raw_file
599
+ if path is None or raw_file is None:
600
+ raise RuntimeError("JsonlRecordEmitter part state is inconsistent")
601
+
602
+ raw_file.write(self._current_compressor.flush())
603
+ raw_file.write(struct.pack(
604
+ "<II",
605
+ self._current_crc & 0xffffffff,
606
+ self._current_part_uncompressed_bytes & 0xffffffff,
607
+ ))
608
+ self._current_compressor = None
609
+ raw_file.flush()
610
+ os.fsync(raw_file.fileno())
611
+ raw_file.close()
612
+
613
+ # fsync parent directory for metadata durability
614
+ dir_fd = os.open(self._output_dir, os.O_RDONLY)
615
+ try:
616
+ os.fsync(dir_fd)
617
+ finally:
618
+ os.close(dir_fd)
619
+
620
+ self._total_bytes_written += os.path.getsize(path)
621
+ self._chunk_index += 1
622
+ self._current_part_path = None
623
+ self._current_raw_file = None
624
+ self._current_part_uncompressed_bytes = 0
625
+ self._current_crc = 0
626
+
627
+ def _ensure_part_open(self) -> None:
628
+ """Open success_part_{index}.jsonl.gz lazily on first record."""
629
+ if self._current_compressor is not None:
630
+ return
631
+
632
+ os.makedirs(self._output_dir, exist_ok=True)
633
+ path = os.path.join(
634
+ self._output_dir, f"success_part_{self._chunk_index}.jsonl.gz"
635
+ )
636
+ raw_file = open(path, "wb")
637
+ raw_file.write(_GZIP_HEADER)
638
+ self._current_part_path = path
639
+ self._current_raw_file = raw_file
640
+ self._current_compressor = zlib.compressobj(
641
+ level=9,
642
+ method=zlib.DEFLATED,
643
+ wbits=-zlib.MAX_WBITS,
644
+ )
645
+ self._current_part_uncompressed_bytes = 0
646
+ self._current_crc = 0
647
+
648
+ def _encode_record(self, record: dict[str, Any]) -> bytes:
649
+ """Encode one record as a UTF-8 JSONL line (newline included).
650
+
651
+ Projects source field names to target load keys via plan.fields and
652
+ plan.system_fields. Each value is encoded per spec L596-604 using
653
+ _json_value (type-aware coercion) with _json_default_fallback for any
654
+ types that survive into nested structures that json.dumps would reject.
655
+ """
656
+ output: dict[str, Any] = {}
657
+
658
+ for binding in self._plan.fields:
659
+ value = record.get(binding.source_name)
660
+ payload_value = _json_payload_value(
661
+ value,
662
+ binding,
663
+ self._max_fractional_second_digits,
664
+ )
665
+ if payload_value is not _OMIT_FIELD:
666
+ output[binding.target_load_key] = payload_value
667
+
668
+ for sys_binding in self._plan.system_fields:
669
+ value = record.get(sys_binding.field.column_name)
670
+ if (
671
+ sys_binding.field == SupaflowSystemField.SUPA_SYNCED
672
+ and self._max_fractional_second_digits is not None
673
+ ):
674
+ value = encode_temporal_stage_value(
675
+ value,
676
+ "INSTANT",
677
+ self._max_fractional_second_digits,
678
+ )
679
+ output[sys_binding.target_load_key] = _json_value(value)
680
+
681
+ return (
682
+ _precision_json.dumps(output, ensure_ascii=False, default=_json_default_fallback).encode("utf-8")
683
+ + b"\n"
684
+ )
685
+
686
+ def _debug_object_name(self) -> str:
687
+ meta = self._plan.source_output_metadata
688
+ if isinstance(meta, dict):
689
+ return str(meta.get("name") or meta.get("fullyQualifiedName") or "")
690
+ return str(
691
+ getattr(meta, "name", None)
692
+ or getattr(meta, "fully_qualified_name", None)
693
+ or ""
694
+ )
695
+
696
+ def _record_debug_fingerprint(self, record: dict[str, Any]) -> None:
697
+ """Accumulate output-level hashes when SUPAFLOW_DEBUG_SUPA_ID is on.
698
+
699
+ These hashes let us prove whether row content and _supa_id changed
700
+ independently without logging complete records. ``business_rows_hash``
701
+ excludes Supaflow system fields; ``supa_id_list_hash`` includes only
702
+ the ordered emitted _supa_id values.
703
+ """
704
+ if not supa_id_debug_enabled():
705
+ return
706
+
707
+ system_names = {name.lower() for name in SUPA_SYSTEM_COLUMNS}
708
+ business = {
709
+ key: _json_value(value)
710
+ for key, value in sorted(record.items())
711
+ if key.lower() not in system_names and not key.startswith("_dlt_")
712
+ }
713
+ business_payload = _precision_json.dumps(
714
+ business,
715
+ sort_keys=True,
716
+ ensure_ascii=False,
717
+ default=_json_default_fallback,
718
+ )
719
+ row_business_hash = hashlib.sha256(business_payload.encode("utf-8")).hexdigest()
720
+ supa_id = str(record.get("_supa_id") or "")
721
+
722
+ self._debug_business_hasher.update(row_business_hash.encode("utf-8"))
723
+ self._debug_business_hasher.update(b"\n")
724
+ self._debug_supa_id_hasher.update(supa_id.encode("utf-8"))
725
+ self._debug_supa_id_hasher.update(b"\n")
726
+ if len(self._debug_first_samples) < 3:
727
+ self._debug_first_samples.append(f"{row_business_hash}->{supa_id}")