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,1052 @@
1
+ """Typed request/response dataclasses for the Supaflow connector SDK.
2
+
3
+ These are the public-facing types that connector developers use when
4
+ implementing the :class:`~supaflow_python_sdk.base_connector.BaseConnector`
5
+ interface. All models are plain :mod:`dataclasses` so they are easy to
6
+ construct, compare, and serialize without any runtime dependencies.
7
+
8
+ Imports
9
+ -------
10
+ :class:`~supaflow_python_sdk.errors.Warning` is re-used from the errors module
11
+ rather than duplicated here.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ from .keyless_object_handling import KeylessObjectHandling
16
+
17
+ from dataclasses import dataclass, field
18
+ from typing import Any
19
+
20
+ from supaflow_python_sdk.errors import Warning # noqa: F401 -- re-exported for convenience
21
+ from supaflow_python_sdk.job_context import _JobContextCarrier
22
+ from supaflow_python_sdk.write_plan import RecordWritePlan # noqa: F401 -- re-exported for transport
23
+
24
+
25
+ # ---------------------------------------------------------------------------
26
+ # Shared types
27
+ # ---------------------------------------------------------------------------
28
+
29
+
30
+ @dataclass
31
+ class MetadataField:
32
+ """Describes a single field in a source or destination schema.
33
+
34
+ Attributes:
35
+ name: Canonical (normalized) field name used inside the pipeline.
36
+ canonical_type: Supaflow canonical type string, one of:
37
+ ``STRING``, ``INT``, ``LONG``, ``DOUBLE``, ``FLOAT``,
38
+ ``BOOLEAN``, ``BIGDECIMAL``, ``LOCALDATE``, ``LOCALDATETIME``,
39
+ ``INSTANT``, ``BINARY``, ``JSON``, ``XML``.
40
+ original_name: Raw field name as returned by the source system.
41
+ ``None`` when name was not transformed.
42
+ selected: Whether the field is included in the sync.
43
+ primary_key: In a runtime ``ReadRequest``, whether the field is part
44
+ of the orchestrator's effective business key. This is the merged
45
+ result of the user's wizard/API selection and the connector's
46
+ discovery ``source_primary_key`` default. It is not Supaflow's
47
+ internal ``_supa_id`` merge pseudokey.
48
+ unique: Whether the field has a unique constraint.
49
+ deletion_indicator: Whether the field signals logical deletion.
50
+ cursor_field: Whether the field is used as an incremental cursor.
51
+ precision: Numeric precision (significant digits), if applicable.
52
+ scale: Numeric scale (decimal places), if applicable.
53
+ """
54
+
55
+ name: str
56
+ canonical_type: str
57
+ original_name: str | None = None
58
+ original_data_type: str | None = None
59
+ selected: bool = True
60
+ primary_key: bool = False
61
+ unique: bool = False
62
+ deletion_indicator: bool = False
63
+ cursor_field: bool = False
64
+ precision: int | None = None
65
+ scale: int | None = None
66
+
67
+
68
+ # ---------------------------------------------------------------------------
69
+ # Init
70
+ # ---------------------------------------------------------------------------
71
+
72
+
73
+ @dataclass
74
+ class InitRequest(_JobContextCarrier):
75
+ """Request payload for the connector initialisation phase.
76
+
77
+ Attributes:
78
+ request_id: Unique identifier for this request (UUID string).
79
+ config: Connector-specific configuration key/value map as provided
80
+ by the user through the Supaflow wizard.
81
+ work_dir: Absolute path to a temporary working directory the
82
+ connector may use during this request.
83
+ """
84
+
85
+ request_id: str
86
+ config: dict[str, Any]
87
+ work_dir: str
88
+
89
+
90
+ @dataclass
91
+ class InitResult:
92
+ """Result returned by the connector initialisation phase.
93
+
94
+ Attributes:
95
+ product_name: Human-readable name of the source product or service
96
+ (e.g. ``"Salesforce Marketing Cloud"``).
97
+ product_version: Version string of the source product detected
98
+ during initialisation (e.g. ``"Spring '24"``).
99
+ supports_targeted_destination_metadata_lookup: Whether this initialized
100
+ connector configuration can resolve exact mapped destination objects.
101
+ """
102
+
103
+ product_name: str
104
+ product_version: str
105
+ supports_targeted_destination_metadata_lookup: bool = False
106
+
107
+
108
+ # ---------------------------------------------------------------------------
109
+ # Stage
110
+ # ---------------------------------------------------------------------------
111
+
112
+
113
+ @dataclass
114
+ class StageStats:
115
+ """Row and byte-level statistics from a staging operation.
116
+
117
+ Attributes:
118
+ row_count: Number of data rows written to the stage location.
119
+ file_count: Number of output files created.
120
+ duration_ms: Wall-clock duration of the staging operation in
121
+ milliseconds.
122
+ bytes_written: Total bytes written to the stage location.
123
+ ``None`` when the connector does not track byte-level metrics.
124
+ """
125
+
126
+ row_count: int
127
+ file_count: int
128
+ duration_ms: int
129
+ bytes_written: int | None = None
130
+
131
+
132
+ @dataclass
133
+ class StageManifest:
134
+ """Describes staged data so the loader knows where and how to load it.
135
+
136
+ The manifest is the contract between the staging step and the loading
137
+ step. It carries everything the loader needs: file locations, schema,
138
+ and statistics.
139
+
140
+ Attributes:
141
+ manifest_version: Schema version of this manifest structure.
142
+ Currently ``1``.
143
+ job_details_id: Foreign key to the ``job_details_v2`` row that
144
+ produced this staged data.
145
+ sync_time: ISO-8601 timestamp representing the point-in-time of
146
+ this sync batch.
147
+ target_schema: Destination schema (database schema / dataset) name,
148
+ or ``None`` for schema-less destinations.
149
+ target_object: Destination table / object name.
150
+ target_fully_qualified_name: Fully-qualified destination name
151
+ (e.g. ``"raw.accounts"``), or ``None`` when a schema is absent.
152
+ stage_location: Root URI of the staging area (e.g. an S3 bucket
153
+ prefix).
154
+ base_location: URI prefix under which all ``output_files`` live.
155
+ output_files: List of file names (relative to ``base_location``)
156
+ that contain staged data.
157
+ table_format: File format used for output files.
158
+ One of ``"PARQUET"`` or ``"CSV"``.
159
+ partition_strategy: Partitioning strategy applied to output files.
160
+ One of ``"NONE"``, ``"DAY"``, or ``"HOUR"``.
161
+ partition_values: Map of partition column names to their values for
162
+ this batch (e.g. ``{"year": "2024", "month": "01"}``), or
163
+ ``None`` when ``partition_strategy`` is ``"NONE"``.
164
+ fields: Ordered list of :class:`MetadataField` objects describing
165
+ the columns present in the output files.
166
+ stats: Row/byte statistics for this staging batch.
167
+ write_metadata: Optional connector-specific metadata that the
168
+ loader may need (e.g. Glue table ARN, Apache Iceberg snapshot ID).
169
+ The structure is connector-defined.
170
+ """
171
+
172
+ manifest_version: int
173
+ job_details_id: str
174
+ sync_time: str
175
+ target_schema: str | None
176
+ target_object: str
177
+ target_fully_qualified_name: str | None
178
+ stage_location: str
179
+ base_location: str
180
+ output_files: list[str]
181
+ table_format: str
182
+ partition_strategy: str
183
+ partition_values: dict[str, str] | None
184
+ fields: list[MetadataField]
185
+ stats: StageStats
186
+ write_metadata: dict[str, Any] | None = None
187
+
188
+
189
+ @dataclass
190
+ class StageRequest(_JobContextCarrier):
191
+ """Request payload for the staging phase.
192
+
193
+ Attributes:
194
+ request_id: Unique identifier for this request (UUID string).
195
+ config: Connector-specific configuration key/value map.
196
+ local_data_path: Absolute path to the local CSV file produced by
197
+ the ingestion phase.
198
+ job_id: Identifier of the parent pipeline job.
199
+ job_details_id: Identifier of the specific job-details row for this
200
+ object.
201
+ sync_time: ISO-8601 timestamp for this sync batch.
202
+ object_name: Source object name (table / endpoint name).
203
+ schema_name: Source schema name, or ``None`` for schema-less
204
+ sources.
205
+ fully_qualified_name: Fully-qualified source object name, or
206
+ ``None`` when a catalog/schema is absent.
207
+ metadata_fields: Schema of the data in ``local_data_path``.
208
+ work_dir: Absolute path to a temporary working directory.
209
+ cancel_path: Optional path to a file that, when it exists, signals
210
+ the connector to abort the current operation gracefully.
211
+ """
212
+
213
+ request_id: str
214
+ config: dict[str, Any]
215
+ local_data_path: str
216
+ job_id: str
217
+ job_details_id: str
218
+ sync_time: str
219
+ object_name: str
220
+ schema_name: str | None
221
+ fully_qualified_name: str | None
222
+ metadata_fields: list[MetadataField]
223
+ work_dir: str
224
+ cancel_path: str | None = None
225
+
226
+ # Transport fields from Java SDK (optional for backward compatibility)
227
+ file_format: str | None = None
228
+ load_mode: str | None = None
229
+ destination_table_handling: str | None = None
230
+ load_optimization_mode: str | None = None
231
+ checksum_validation_level: str | None = None
232
+ error_handling: str | None = None
233
+ perform_hard_deletes: bool = False
234
+ metadata_context: MetadataContext | None = None
235
+ csv_null_marker: str | None = None
236
+ zero_rows: bool = False
237
+ # Run-intent flags (additive; old hosts omit them and defaults apply).
238
+ # reset_target lets final-file destinations act BEFORE uploading instead of
239
+ # inferring reset from forced load modes.
240
+ reset_target: bool = False
241
+ full_resync: bool = False
242
+ initial_sync: bool = False
243
+ run_reason: str | None = None
244
+
245
+ keyless_object_handling: KeylessObjectHandling = field(
246
+ default=KeylessObjectHandling.UUID, kw_only=True
247
+ )
248
+
249
+ def __post_init__(self) -> None:
250
+ self.keyless_object_handling = KeylessObjectHandling.parse(self.keyless_object_handling)
251
+
252
+
253
+ @dataclass
254
+ class StageResult:
255
+ """Result returned by the staging phase.
256
+
257
+ Attributes:
258
+ manifest: Manifest describing the staged data. Always present on
259
+ success.
260
+ duration_ms: Total wall-clock duration of the staging operation in
261
+ milliseconds as measured by the host. ``None`` if not measured.
262
+ warnings: Non-fatal advisories collected during staging, or ``None``
263
+ when there are no warnings.
264
+ """
265
+
266
+ manifest: StageManifest
267
+ duration_ms: int | None = None
268
+ warnings: list[Warning] | None = None
269
+
270
+
271
+ # ---------------------------------------------------------------------------
272
+ # Load
273
+ # ---------------------------------------------------------------------------
274
+
275
+
276
+ @dataclass
277
+ class MetadataContext:
278
+ """Normalized destination-state metadata for schema evolution and merge decisions.
279
+
280
+ Transported as a flat DTO from the Java PipelineMetadataMappingAndSourceMetadataCatalog.
281
+ Only the fields needed for load-time decisions are included.
282
+
283
+ Attributes:
284
+ mapped_merged_fields: Current selected fields in destination namespace.
285
+ last_applied_fields: Fields from last successful apply (for schema diff).
286
+ destination_fields: Fields currently in destination table (for ALTER decisions).
287
+ selected_merge_keys: User-selected merge key field names for UPSERT.
288
+ object_name: Destination object name.
289
+ schema_name: Destination schema name.
290
+ destination_applied: True when the destination has been applied at least
291
+ once (derived from ``destinationAppliedAt != null`` on the Java side).
292
+ Used together with ``last_applied_fields`` for first-run detection:
293
+ a run is first-run only when both are falsy.
294
+ """
295
+
296
+ mapped_merged_fields: list[MetadataField] | None = None
297
+ last_applied_fields: list[MetadataField] | None = None
298
+ destination_fields: list[MetadataField] | None = None
299
+ selected_merge_keys: list[str] | None = None
300
+ object_name: str | None = None
301
+ schema_name: str | None = None
302
+ destination_applied: bool | None = None
303
+
304
+
305
+ @dataclass
306
+ class RemoteLoadArtifact:
307
+ """Pre-staged remote artifact (e.g. S3 files) a destination loader can
308
+ consume directly, bypassing local staging.
309
+
310
+ Mirrors the Java ``io.supaflow.connector.sdk.model.RemoteLoadArtifact``.
311
+ A source connector that writes files straight to cloud storage returns
312
+ this on a ``ReadResult`` (when the host set
313
+ ``ReadRequest.direct_remote_load_requested``); the host then hands it to
314
+ the loading phase via ``LoadRequest.remote_load_artifact`` so the
315
+ destination can issue a native COPY (e.g. Redshift/Snowflake COPY from S3)
316
+ instead of re-uploading data.
317
+
318
+ Wire shape (camelCase, produced by Jackson on the Java POJO):
319
+ ``s3Uri``, ``fieldOrder``, ``csvFileFormat``, ``csvHeaderMode``,
320
+ ``fieldEncodings``, ``fileCount``, ``byteCount``. The protocol layer
321
+ (:mod:`supaflow_python_runtime.protocol`) round-trips this dataclass the
322
+ same way it does ``RecordWritePlan`` -- camelCase keys map to these
323
+ snake_case fields via ``_dict_to_dataclass`` / ``_dataclass_to_dict``.
324
+
325
+ Attributes:
326
+ s3_uri: Root S3 URI (or prefix) the artifact files live under.
327
+ field_order: Column order the files were written in. Mirrors Java
328
+ ``fieldOrder`` (``List<String>``).
329
+ csv_header_mode: The Java ``CsvHeaderMode`` enum **name** -- one of
330
+ ``"NONE"``, ``"COLUMN_NAMES"``, ``"COLUMN_NAMES_AND_TYPES"``.
331
+ ``None`` when unset.
332
+ csv_file_format: Opaque CSV file-format options as a JSON ``dict``,
333
+ NOT a typed dataclass. The Java ``CsvFileFormat`` extends a
334
+ polymorphic ``FileFormat`` with ``@JsonNaming(SnakeCaseStrategy)``
335
+ and a ``"type"`` discriminator, so Jackson serializes its members
336
+ in **snake_case** (``field_delimiter``, ``skip_header``,
337
+ ``empty_field_as_null``, ...) plus ``"type": "CSV"``. Keeping this
338
+ a verbatim ``dict`` preserves that exact JSON; a typed Python
339
+ dataclass would be re-serialized to camelCase by the protocol and
340
+ break the round-trip. Treat the keys as snake_case (matching the
341
+ Java JSON).
342
+ field_encodings: Sparse field-name -> Java ``RemoteFieldEncoding`` enum
343
+ name map. Set only when a field's remote artifact representation
344
+ differs from its logical destination type, for example
345
+ ``{"payload": "UTF8_JSON_HEX"}``.
346
+ file_count: Number of artifact files, or ``None``. Mirrors the Java
347
+ ``OptionalLong fileCount`` (absent -> ``None``).
348
+ byte_count: Total artifact size in bytes, or ``None``. Mirrors the
349
+ Java ``OptionalLong byteCount`` (absent -> ``None``).
350
+ """
351
+
352
+ s3_uri: str | None = None
353
+ field_order: list[str] = field(default_factory=list)
354
+ csv_header_mode: str | None = None
355
+ csv_file_format: dict[str, Any] | None = None
356
+ field_encodings: dict[str, str] = field(default_factory=dict)
357
+ file_count: int | None = None
358
+ byte_count: int | None = None
359
+
360
+
361
+ @dataclass
362
+ class LoadRequest(_JobContextCarrier):
363
+ """Request payload for the loading phase.
364
+
365
+ Attributes:
366
+ request_id: Unique identifier for this request (UUID string).
367
+ config: Connector-specific configuration key/value map.
368
+ job_details_id: Identifier of the specific job-details row for this
369
+ object.
370
+ manifest: Manifest from the preceding staging phase that describes
371
+ which files to load and where to put them.
372
+ work_dir: Absolute path to a temporary working directory.
373
+ """
374
+
375
+ request_id: str
376
+ config: dict[str, Any]
377
+ job_details_id: str
378
+ manifest: StageManifest
379
+ work_dir: str
380
+
381
+ # Transport fields from Java SDK (optional for backward compatibility)
382
+ load_mode: str | None = None
383
+ destination_table_handling: str | None = None
384
+ zero_rows: bool = False
385
+ is_ddl_only: bool = False
386
+ checksum_validation_level: str | None = None
387
+ error_handling: str | None = None
388
+ perform_hard_deletes: bool = False
389
+ load_optimization_mode: str | None = None
390
+ file_format: str | None = None
391
+ local_data_path: str | None = None
392
+ sync_time: str | None = None
393
+ metadata_context: MetadataContext | None = None
394
+ csv_null_marker: str | None = None
395
+ # Run-intent flags (additive; old hosts omit them and defaults apply).
396
+ # load_mode remains the reset-forced value on reset runs; reset_target
397
+ # removes the ambiguity with a configured OVERWRITE.
398
+ reset_target: bool = False
399
+ full_resync: bool = False
400
+ initial_sync: bool = False
401
+ run_reason: str | None = None
402
+ # Pre-staged remote artifact for direct-load destinations (Redshift/Snowflake
403
+ # COPY from S3). Populated by the host from the source read's
404
+ # ReadResult.remote_load_artifact when a direct external-stage load was
405
+ # requested; None on the normal staged path. Bridge serializes it as
406
+ # camelCase remoteLoadArtifact (omit-when-null).
407
+ remote_load_artifact: RemoteLoadArtifact | None = None
408
+
409
+ keyless_object_handling: KeylessObjectHandling = field(
410
+ default=KeylessObjectHandling.UUID, kw_only=True
411
+ )
412
+
413
+ def __post_init__(self) -> None:
414
+ self.keyless_object_handling = KeylessObjectHandling.parse(self.keyless_object_handling)
415
+
416
+
417
+ @dataclass
418
+ class ChecksumMetrics:
419
+ """Destination-side validation metrics returned after loading.
420
+
421
+ Attributes:
422
+ level: Validation level (NONE, ROW_COUNT, COLUMN_STATISTICS, FULL_INTEGRITY).
423
+ row_count: Number of rows in destination after load.
424
+ null_counts: Per-column null counts (for COLUMN_STATISTICS level).
425
+ distinct_counts: Per-column distinct counts (for COLUMN_STATISTICS level).
426
+ data_hashes: Sample data hashes (for FULL_INTEGRITY level).
427
+ error_message: Error message if counting failed.
428
+ """
429
+
430
+ level: str | None = None
431
+ row_count: int | None = None
432
+ null_counts: dict[str, int] | None = None
433
+ distinct_counts: dict[str, int] | None = None
434
+ data_hashes: dict[str, str] | None = None
435
+ error_message: str | None = None
436
+
437
+
438
+ @dataclass
439
+ class LoadResult:
440
+ """Result returned by the loading phase.
441
+
442
+ Attributes:
443
+ message: Optional human-readable summary of the load operation
444
+ (e.g. ``"Loaded 1 024 rows into raw.accounts"``).
445
+ success_count: Number of rows successfully loaded, or ``None`` if
446
+ the connector does not track per-load row counts.
447
+ error_count: Number of rows that failed to load, or ``None``.
448
+ inserted_count: Rows inserted (APPEND/INSERT operations), or ``None``
449
+ if the connector does not distinguish DML types.
450
+ updated_count: Rows updated (MERGE/UPSERT operations), or ``None``.
451
+ deleted_count: Rows deleted, or ``None``.
452
+ checksum_metrics: Destination-side validation metrics, or ``None``.
453
+ warnings: Non-fatal advisories collected during loading, or ``None``
454
+ when there are no warnings.
455
+ """
456
+
457
+ message: str | None = None
458
+ success_count: int | None = None
459
+ error_count: int | None = None
460
+ inserted_count: int | None = None
461
+ updated_count: int | None = None
462
+ deleted_count: int | None = None
463
+ checksum_metrics: ChecksumMetrics | None = None
464
+ warnings: list[Warning] | None = None
465
+
466
+
467
+ # ---------------------------------------------------------------------------
468
+ # Map Target Object
469
+ # ---------------------------------------------------------------------------
470
+
471
+
472
+ @dataclass
473
+ class ProposedField:
474
+ """A field name proposed by the pipeline engine before mapping.
475
+
476
+ Attributes:
477
+ original_name: Raw field name from the source system.
478
+ proposed_name: Name proposed by the engine after applying naming
479
+ conventions (e.g. snake_case normalisation).
480
+ canonical_type: Supaflow canonical type string for this field.
481
+ """
482
+
483
+ original_name: str
484
+ proposed_name: str
485
+ canonical_type: str
486
+
487
+
488
+ @dataclass
489
+ class MappedField:
490
+ """A source field name resolved to its final destination name.
491
+
492
+ Attributes:
493
+ original_name: Raw field name from the source system.
494
+ mapped_name: Definitive destination field name after connector
495
+ mapping logic has been applied.
496
+ """
497
+
498
+ original_name: str
499
+ mapped_name: str
500
+
501
+
502
+ @dataclass
503
+ class ExistingTarget:
504
+ """Describes a destination object that already exists.
505
+
506
+ Passed to :class:`MapTargetObjectRequest` when the target table has
507
+ been created in a previous sync cycle.
508
+
509
+ Attributes:
510
+ schema_name: Destination schema name, or ``None`` for schema-less
511
+ destinations.
512
+ object_name: Destination table / object name.
513
+ fully_qualified_name: Fully-qualified destination name.
514
+ fields: Current field mapping as recorded in the last successful
515
+ sync.
516
+ """
517
+
518
+ schema_name: str | None
519
+ object_name: str
520
+ fully_qualified_name: str
521
+ fields: list[MappedField]
522
+
523
+
524
+ @dataclass
525
+ class MapTargetObjectRequest(_JobContextCarrier):
526
+ """Request payload for the target-object mapping phase.
527
+
528
+ The connector uses this information to decide (or confirm) the final
529
+ destination schema, object name, and field names -- taking into account
530
+ any existing target state.
531
+
532
+ Attributes:
533
+ request_id: Unique identifier for this request (UUID string).
534
+ config: Connector-specific configuration key/value map.
535
+ source_catalog: Source catalog name, or ``None`` for catalog-less
536
+ sources.
537
+ source_schema: Source schema name, or ``None`` for schema-less
538
+ sources.
539
+ source_object_name: Source object name (table / endpoint name).
540
+ source_fields: Schema of the source object.
541
+ proposed_schema_name: Schema name proposed by the pipeline engine,
542
+ or ``None`` for schema-less destinations.
543
+ proposed_object_name: Object name proposed by the pipeline engine.
544
+ proposed_fields: List of field name/type proposals from the engine.
545
+ existing_target: Current state of the destination object if it was
546
+ previously created, or ``None`` on first sync.
547
+ """
548
+
549
+ request_id: str
550
+ config: dict[str, Any]
551
+ source_catalog: str | None
552
+ source_schema: str | None
553
+ source_object_name: str
554
+ source_fields: list[MetadataField]
555
+ proposed_schema_name: str | None
556
+ proposed_object_name: str
557
+ proposed_fields: list[ProposedField]
558
+ existing_target: ExistingTarget | None = None
559
+
560
+
561
+ @dataclass
562
+ class MapTargetObjectResult:
563
+ """Result returned by the target-object mapping phase.
564
+
565
+ Attributes:
566
+ schema_name: Final destination schema name, or ``None`` for
567
+ schema-less destinations.
568
+ object_name: Final destination object / table name.
569
+ fully_qualified_name: Final fully-qualified destination name, or
570
+ ``None`` when a schema is absent.
571
+ fields: Resolved field mappings: one :class:`MappedField` per
572
+ source field, in source order.
573
+ """
574
+
575
+ schema_name: str | None
576
+ object_name: str
577
+ fully_qualified_name: str | None
578
+ fields: list[MappedField]
579
+
580
+
581
+ # ---------------------------------------------------------------------------
582
+ # Schema Discovery
583
+ # ---------------------------------------------------------------------------
584
+
585
+
586
+ @dataclass
587
+ class SchemaFieldInfo:
588
+ """Mirrors io.supaflow.core.model.metadata.FieldMetadata (schema subset).
589
+
590
+ Capability flags (cursor_capable, primary_key_capable) and source flags
591
+ (source_cursor_field, source_primary_key) follow the Java contract:
592
+ - Capability flags: must be non-None for strict compliance.
593
+ - Source flags: sparse booleans -- True or None only, never False.
594
+ - Selection flags (cursor_field, primary_key): must NOT be set in
595
+ discovery output; these are owned by the merge/selection layer.
596
+ - ``_supa_id`` is an internal merge pseudokey. A connector must not mark
597
+ it as ``source_primary_key`` or ``primary_key`` in discovery output.
598
+ """
599
+ name: str
600
+ canonical_type: str
601
+ original_data_type: str | None = None
602
+ description: str | None = None
603
+ # Capability flags -- set by connectors during schema discovery
604
+ cursor_capable: bool | None = None
605
+ primary_key_capable: bool | None = None
606
+ # Source flags -- sparse booleans (True or None, never False)
607
+ source_cursor_field: bool | None = None
608
+ source_primary_key: bool | None = None
609
+ # Numeric precision/scale -- set when canonical_type is BIGDECIMAL
610
+ precision: int | None = None
611
+ scale: int | None = None
612
+ # Selection flags -- NOT set during discovery (owned by merge layer)
613
+ cursor_field: bool | None = None
614
+ primary_key: bool | None = None
615
+
616
+
617
+ @dataclass
618
+ class SchemaObjectInfo:
619
+ """Mirrors io.supaflow.core.model.metadata.ObjectMetadata (schema subset).
620
+
621
+ Note on the two `type` fields -- they are distinct and not
622
+ interchangeable:
623
+
624
+ - `type`: SQL/catalog object type string. Valid values include
625
+ "TABLE", "VIEW", "MATERIALIZED_VIEW", etc. Maps to Java's
626
+ ObjectMetadata.type, which is persisted to
627
+ source_metadata_catalog.object_type and describes WHAT KIND of
628
+ database object this is from the source system's perspective.
629
+
630
+ - `object_type`: Supaflow orchestration role. Valid values are
631
+ "PRIMARY", "ASSOCIATION", "HISTORY", "METADATA". Maps to Java's
632
+ ObjectMetadata.objectType (an ObjectType enum), which is persisted
633
+ to source_metadata_catalog.supa_object_type and drives Supaflow's
634
+ pipeline orchestration. Specifically, PipelineOrchestrator.java
635
+ only builds parent-child execution linkage for jobs whose
636
+ supa_object_type is ASSOCIATION or HISTORY. A child object with
637
+ parent_object_name set but object_type = "PRIMARY" (the Java-side
638
+ default) will be silently treated as a top-level job.
639
+ """
640
+ name: str
641
+ schema: str | None = None
642
+ catalog: str | None = None
643
+ type: str | None = None
644
+ fully_qualified_name: str | None = None
645
+ fields: list[SchemaFieldInfo] | None = None
646
+ incremental_strategy: str | None = None
647
+ identity_strategy: str | None = None
648
+ cursor_field_locked: bool | None = None
649
+ primary_key_locked: bool | None = None
650
+ description: str | None = None
651
+ custom_attributes: dict[str, Any] | None = None
652
+ child_settings: dict[str, Any] | None = None
653
+ parent_object_name: str | None = None
654
+ object_type: str | None = None
655
+ # Structured path-chain for derived child objects produced by
656
+ # dlt's normalize stage from nested JSON. Tuple form
657
+ # ``(root, ..., leaf)`` for derived children; ``None`` for
658
+ # root objects (per Target Contract in
659
+ # docs/superpowers/specs/2026-05-11-dlt-original-source-names-restoration.md).
660
+ # Authoritative wire form between Python and Java for child
661
+ # identity; the joined-string ``name`` / ``fully_qualified_name``
662
+ # is a derived view only. Consumers that decompose a path MUST
663
+ # read ``path_segments`` rather than splitting on ``__``.
664
+ # Populated by Phase 1 sub-step 3 (framework wiring under the
665
+ # preserve_original_names flag); unused / left None until then.
666
+ path_segments: tuple[str, ...] | None = None
667
+ # Source/runtime-driven object exclusion. These fields mirror ObjectMetadata's
668
+ # runtime skip contract so a Python connector can publish an object that
669
+ # exists but is not readable with the current source capabilities.
670
+ skipped: bool | None = None
671
+ skipped_reason: str | None = None
672
+ skipped_reason_detail: str | None = None
673
+
674
+
675
+ @dataclass
676
+ class SchemaInfo:
677
+ """Mirrors io.supaflow.core.metadata.SchemaMetadata."""
678
+ name: str
679
+ full_name: str | None = None
680
+ catalog: str | None = None
681
+
682
+
683
+ @dataclass
684
+ class SchemaCatalogInfo:
685
+ """Mirrors io.supaflow.core.metadata.CatalogMetadata."""
686
+ name: str | None = None
687
+ schemas: list[SchemaInfo] | None = None
688
+
689
+
690
+ @dataclass
691
+ class SchemaRequest(_JobContextCarrier):
692
+ request_id: str
693
+ config: dict[str, Any]
694
+ level: str # "SCHEMAS_ONLY", "TABLES_ONLY", "FULL"
695
+ work_dir: str
696
+ schema_list: list[SchemaInfo] | None = None
697
+ table_list: list[str] | None = None
698
+ types: list[str] | None = None # ["TABLE", "VIEW"]
699
+ fetch_constraints: bool = False
700
+ cancel_path: str | None = None
701
+
702
+
703
+ @dataclass
704
+ class SchemaResult:
705
+ catalogs: list[SchemaCatalogInfo] | None = None
706
+ objects: list[SchemaObjectInfo] | None = None
707
+
708
+
709
+ # ---------------------------------------------------------------------------
710
+ # Read (Source) -- Supporting DTOs
711
+ # ---------------------------------------------------------------------------
712
+
713
+
714
+ @dataclass
715
+ class FilterItem:
716
+ """Operand in a filter condition."""
717
+ value: str
718
+ type: str # "value" or "column"
719
+
720
+
721
+ @dataclass
722
+ class FilterCondition:
723
+ """A single filter condition for read operations."""
724
+ left: FilterItem
725
+ exp: str # eq, notEq, gt, gte, lt, lte
726
+ right: FilterItem
727
+
728
+
729
+ @dataclass
730
+ class OrderByClause:
731
+ """Ordering clause for read operations."""
732
+ field: str
733
+ direction: str # ASC, DESC
734
+ nulls: str | None = None # FIRST, LAST
735
+
736
+
737
+ @dataclass
738
+ class IncrementalField:
739
+ """Cursor position for incremental sync."""
740
+ field_name: str
741
+ value: str | None = None
742
+ record_count: int | None = None
743
+ max_value_seen: str | None = None
744
+
745
+
746
+ @dataclass
747
+ class SyncStateRequest:
748
+ """Sync state passed to a read operation (cursor position from previous run)."""
749
+ object_name: str | None = None
750
+ cursor_position: list[IncrementalField] | None = None
751
+ cutoff_time: str | None = None
752
+ initial_sync: bool = True
753
+ custom_state: dict[str, Any] | None = None
754
+
755
+
756
+ @dataclass
757
+ class AppliedReadWindow:
758
+ """Exact half-open read window the connector APPLIED this run.
759
+
760
+ Reported post-clamping by connector-managed date-window sources so the
761
+ loader can delete exactly this range pre-MERGE (windowed replace).
762
+ The loader never recomputes the window: history caps (e.g. click_view
763
+ 90 days) mean a recomputed window could cover never-re-read rows.
764
+ ``end_exclusive`` is exclusive -- date-inclusive APIs report
765
+ ``applied_end_date + 1 day``.
766
+ """
767
+ cursor_field: str
768
+ start_inclusive: str
769
+ end_exclusive: str
770
+
771
+
772
+ @dataclass
773
+ class SyncStateResponse:
774
+ """Sync state returned from a read operation (new cursor position)."""
775
+ end_cursor_position: list[IncrementalField] | None = None
776
+ custom_state: dict[str, Any] | None = None
777
+ records_processed: int = 0
778
+ request_reset_target: bool = False
779
+ applied_read_window: AppliedReadWindow | None = None
780
+
781
+
782
+ @dataclass
783
+ class RetryPolicy:
784
+ """Retry configuration hint for read operations."""
785
+ max_attempts: int = 3
786
+ initial_delay_ms: int = 1000
787
+ max_delay_ms: int = 30000
788
+ multiplier: float = 2.0
789
+ jitter: bool = True
790
+
791
+
792
+ @dataclass
793
+ class RateLimitConfig:
794
+ """Rate limiting configuration hint for read operations."""
795
+ permits_per_second: float = 0.0
796
+ burst: int = 1
797
+ max_sleep_ms: int = 60000
798
+
799
+
800
+ @dataclass
801
+ class ReadObjectMetadata:
802
+ """Flattened object metadata for read operations.
803
+
804
+ Normalized from Java ObjectMetadata which is too complex to serialize.
805
+ """
806
+ name: str
807
+ fields: list[MetadataField]
808
+ schema: str | None = None
809
+ catalog: str | None = None
810
+ fully_qualified_name: str | None = None
811
+ object_type: str | None = None
812
+ parent_table_name: str | None = None
813
+ custom_attributes: dict[str, Any] | None = None
814
+ # Structured root-first path chain mirroring Java
815
+ # ``ObjectMetadata.pathSegments`` (added in PR B, bridge contract
816
+ # migration). Optional and nullable. ``None`` for legacy connectors
817
+ # and root objects. Populated by Java when the source connector has
818
+ # opted into ``preserve_original_names=True``; bridge protocol
819
+ # decodes ``path_segments`` from the JSON payload via the
820
+ # dataclass-driven decode in ``supaflow_python_runtime.protocol``.
821
+ # Typed as ``list[str]`` (matches the JSON-array shape the protocol
822
+ # layer produces). **Consumers MUST NOT split ``name`` or
823
+ # ``fully_qualified_name`` on ``"__"`` to recover this**; the
824
+ # joined form is ambiguous when a source segment contains literal
825
+ # ``"__"``. No consumer in PR B reads or populates this field --
826
+ # downstream wiring lands in PR C and beyond.
827
+ path_segments: list[str] | None = None
828
+
829
+
830
+ @dataclass
831
+ class ChildContextInfo:
832
+ """Info about a child object that depends on this parent's read.
833
+
834
+ The ``writer`` is runtime-injected; the connector uses it to emit rows
835
+ for this child. The meaning of those rows depends on ``delivery_mode``:
836
+
837
+ - ``"CONTEXT"`` (default): parent-derived inputs (typically IDs) written
838
+ to the child's context path. The child connector still runs its own
839
+ source read using those inputs.
840
+ - ``"MATERIALIZED_CHILD_OUTPUT"``: the child object's final output rows
841
+ written directly to the child's data path. The child ingestion phase
842
+ skips source read; stage/load run normally.
843
+
844
+ ``context_fields`` describes the row schema for the delivery stream
845
+ regardless of mode. In CONTEXT mode these are parent-derived context
846
+ fields (None means PK-only, legacy default). In MATERIALIZED_CHILD_OUTPUT
847
+ mode these are the child object's effective filtered output fields.
848
+ """
849
+ child_object_name: str
850
+ child_job_detail_id: str
851
+ writer: Any | None = None # ChildContextWriter or RecordEmitter, runtime-injected
852
+ context_fields: list[MetadataField] | None = None
853
+ delivery_mode: str = "CONTEXT" # "CONTEXT" or "MATERIALIZED_CHILD_OUTPUT"
854
+ # Structured path-chain mirroring the bridge contract added in
855
+ # PR B. Optional and nullable -- absent for every connector that has
856
+ # not opted into ``DltConnectorSpec.preserve_original_names=True``
857
+ # AND is unused on the read path until PR C wires consumers to
858
+ # read it. Populated by the Java bridge from
859
+ # ``ChildContextInfo.pathSegments`` when present; left ``None``
860
+ # otherwise. Typed as ``list[str]`` (not ``tuple``) because the
861
+ # protocol layer decodes JSON arrays into Python lists; framework
862
+ # populators that want immutability can convert to a tuple at
863
+ # the read site. No consumer in this PR splits the joined
864
+ # ``child_object_name`` -- structural decomposition reads this
865
+ # field directly.
866
+ path_segments: list[str] | None = None
867
+
868
+
869
+ @dataclass
870
+ class ReadMetadata:
871
+ """Metadata about a completed read operation.
872
+
873
+ ``fields`` mirrors Java ``ReadMetadata.fields: List<FieldMetadata>`` and
874
+ uses ``MetadataField`` (the runtime field DTO already used by
875
+ ``ReadObjectMetadata.fields``), NOT ``SchemaFieldInfo``. The two DTOs are
876
+ separate on purpose: ``SchemaFieldInfo`` carries schema-discovery output
877
+ (cursor_capable, primary_key_capable, source markers); ``MetadataField``
878
+ carries runtime per-record metadata (selected, primary_key, unique,
879
+ deletion_indicator, cursor_field, precision/scale). RT-2 wired the Java
880
+ bridge's ``mapReadMetadata`` to actually consume this field list.
881
+ """
882
+ fields: list[MetadataField] | None = None
883
+ actual_query: str | None = None
884
+ applied_optimizations: list[str] | None = None
885
+ warnings: list[str] | None = None
886
+
887
+
888
+ @dataclass
889
+ class ReadStatistics:
890
+ """Statistics from a read operation. Durations in milliseconds."""
891
+ records_read: int | None = None
892
+ bytes_read: int | None = None
893
+ error_count: int | None = None
894
+ execution_time_ms: int | None = None
895
+ connection_time_ms: int | None = None
896
+ time_to_first_record_ms: int | None = None
897
+ custom_stats: dict[str, Any] | None = None
898
+
899
+
900
+ @dataclass
901
+ class ProgressUpdatePolicy:
902
+ """Runtime policy for interim read progress updates."""
903
+
904
+ min_rows: int = 10_000
905
+ min_interval_ms: int = 5_000
906
+ heartbeat_interval_ms: int = 30_000
907
+
908
+ def __post_init__(self) -> None:
909
+ if self.min_rows < 1:
910
+ raise ValueError(f"min_rows must be >= 1, got {self.min_rows}")
911
+ if self.min_interval_ms < 0:
912
+ raise ValueError(
913
+ f"min_interval_ms must be >= 0, got {self.min_interval_ms}"
914
+ )
915
+ if self.heartbeat_interval_ms < 0:
916
+ raise ValueError(
917
+ "heartbeat_interval_ms must be >= 0, "
918
+ f"got {self.heartbeat_interval_ms}"
919
+ )
920
+
921
+
922
+ # ---------------------------------------------------------------------------
923
+ # Read (Source) -- Request / Result
924
+ # ---------------------------------------------------------------------------
925
+
926
+
927
+ @dataclass
928
+ class ReadRequest(_JobContextCarrier):
929
+ """Request payload for source read operations.
930
+
931
+ Runtime-injected fields (record_emitter, parent_context_reader,
932
+ checkpoint_emitter, progress_reporter, and child_context_infos[i].writer)
933
+ are created by the host from transport config. They are NOT serialized
934
+ in the protocol.
935
+ """
936
+ request_id: str
937
+ config: dict[str, Any]
938
+ work_dir: str
939
+
940
+ # Runtime-injected (not serialized)
941
+ record_emitter: Any | None = None # RecordEmitter
942
+ parent_context_reader: Any | None = None # ParentContextReader
943
+ checkpoint_emitter: Any | None = None # CheckpointEmitter
944
+ progress_reporter: Any | None = None # ProgressReporter
945
+
946
+ # Object/query
947
+ object_metadata: ReadObjectMetadata | None = None
948
+ custom_query: str | None = None
949
+
950
+ # Filtering, ordering, pagination
951
+ filters: list[FilterCondition] | None = None
952
+ order_by: list[OrderByClause] | None = None
953
+ limit: int | None = None
954
+ offset: int | None = None
955
+ continuation_token: str | None = None
956
+
957
+ # Sync state
958
+ sync_state: SyncStateRequest | None = None
959
+ ingestion_mode: str | None = None
960
+ load_mode: str | None = None
961
+
962
+ # Resource hints
963
+ hints: dict[str, Any] | None = None
964
+ timeout_ms: int | None = None
965
+ recommended_page_size: int | None = None
966
+ target_memory_bytes_per_page: int | None = None
967
+
968
+ # Checkpoint config
969
+ checkpoint_strategy: str | None = None
970
+ checkpoint_interval: int | None = None
971
+ enable_checkpoints: bool = False
972
+
973
+ # Validation
974
+ checksum_validation_level: str | None = None
975
+
976
+ # Job context
977
+ job_details_id: str | None = None
978
+ sync_time: str | None = None
979
+
980
+ # Format decision from Java planner. Python activates JsonlRecordEmitter only when
981
+ # BOTH this field equals "JSONL" AND the env flag is on (dual-gate). When None or
982
+ # "CSV", stays on CSV regardless of the env flag. This makes Java the source of
983
+ # truth for format selection; the env flag is a kill-switch only.
984
+ stage_format: str | None = None
985
+
986
+ # Direct external-stage load hint from the Java planner. When True, a source
987
+ # that writes files directly to cloud storage (e.g. S3) should return a
988
+ # RemoteLoadArtifact on its ReadResult instead of streaming rows, so the
989
+ # destination can issue a native COPY. False on the normal streamed path.
990
+ # Bridge serializes it as camelCase directRemoteLoadRequested (always sent).
991
+ direct_remote_load_requested: bool = False
992
+
993
+ # Mapped Java write plan. Required for JSONL and for CSV when the destination
994
+ # declares a staged temporal-precision policy. Emitters consume this directly
995
+ # so output values follow the destination write contract.
996
+ record_write_plan: RecordWritePlan | None = None
997
+
998
+ # Mapped Java write plans for materialized child emitters, keyed by child object name.
999
+ child_record_write_plans: dict[str, RecordWritePlan] | None = None
1000
+
1001
+ # Retry/rate-limit hints
1002
+ retry_policy: RetryPolicy | None = None
1003
+ rate_limit_config: RateLimitConfig | None = None
1004
+ progress_update_policy: ProgressUpdatePolicy | None = None
1005
+
1006
+ # Child context
1007
+ child_context_infos: list[ChildContextInfo] | None = None
1008
+
1009
+ # Cancellation. PythonConnectorBridge.buildReadPayload writes
1010
+ # `cancelPath` on the wire only when non-null (omit-when-null), so
1011
+ # this field defaults to None to match the Java contract: missing
1012
+ # key means "no cancel-file path supplied for this request." When
1013
+ # non-null, the connector or the runtime host can poll the path for
1014
+ # a cancellation signal -- mirrors StageRequest.cancel_path and
1015
+ # SchemaRequest.cancel_path.
1016
+ cancel_path: str | None = None
1017
+
1018
+ keyless_object_handling: KeylessObjectHandling = field(
1019
+ default=KeylessObjectHandling.UUID, kw_only=True
1020
+ )
1021
+
1022
+ def __post_init__(self) -> None:
1023
+ self.keyless_object_handling = KeylessObjectHandling.parse(self.keyless_object_handling)
1024
+
1025
+
1026
+ @dataclass
1027
+ class ReadResult:
1028
+ """Result returned from a source read operation.
1029
+
1030
+ Terminal status lives here, not in ProgressReporter.
1031
+ No top-level warnings field: Java ReadResponse has no top-level warnings.
1032
+ Warnings belong under ReadMetadata.warnings (list[str]).
1033
+ """
1034
+ status: str # COMPLETED, COMPLETED_WITH_WARNINGS, FAILED, CANCELLED, TIMED_OUT
1035
+
1036
+ metadata: ReadMetadata | None = None
1037
+ next_continuation_token: str | None = None
1038
+ has_more: bool = False
1039
+ statistics: ReadStatistics | None = None
1040
+ error_message: str | None = None
1041
+ sync_state: SyncStateResponse | None = None
1042
+ checksum_metrics: ChecksumMetrics | None = None
1043
+ # Host-populated: per-child row counts keyed by child_job_detail_id.
1044
+ # Connectors must not set this directly; the host harvests from
1045
+ # materialized child writers after connector.read() returns.
1046
+ materialized_child_row_counts: dict[str, int] | None = None
1047
+ # Pre-staged remote artifact (e.g. S3 files) a source connector returns
1048
+ # when ReadRequest.direct_remote_load_requested was set, so the loading
1049
+ # phase can issue a native COPY instead of re-uploading. None on the
1050
+ # normal streamed path. Bridge maps the camelCase remoteLoadArtifact wire
1051
+ # key back to Java ReadResponse.remoteLoadArtifact in mapReadResponse.
1052
+ remote_load_artifact: RemoteLoadArtifact | None = None