Skip to content

fix(codegen): restore codestyle-doc-tests compliance after botocore sync - #6523

Merged
rsareddy0329 merged 3 commits into
aws:masterfrom
rsareddy0329:fix/resources-black-format
Oct 28, 2026
Merged

rsareddy0329 merged 3 commits into
aws:masterfrom
rsareddy0329:fix/resources-black-format

Conversation

@rsareddy0329

Copy link
Copy Markdown
Contributor

Issue

codestyle-doc-tests (sagemaker-core) fails black-check on master: the generated sagemaker-core/src/sagemaker/core/resources.py has two blank lines between the import block and the module logger, which black collapses to one.

Root cause: the import block ends with "\n\n" and LOGGER_STRING (in tools/constants.py) began with a leading "\n", so together they emit an extra blank line.

Description of changes

  • tools/constants.py — drop the leading newline from LOGGER_STRING so the code generator no longer emits the double blank line. This keeps regenerated resources.py black-clean and prevents the next daily Botocore sync from reintroducing the failure (durable fix).
  • resources.py — reformat the currently-committed generated file to match.

Formatting/codegen only — no functional change.

Testing done

With the CI-pinned black==26.3.1 under Python 3.12:

  • black --check on resources.py and constants.py → rc 0
  • flake8 and pydocstyle on both files → clean
  • No unit test pinned the old LOGGER_STRING value.

Note for maintainers

black emitted a "cannot parse code formatted for Python 3.14 … use --target-version or --fast" safety-check warning on resources.py. If the daily-sync black step hit the same warning, black would have skipped reformatting (it won't write when the AST safety check fails unless --fast), which is likely why the extra blank line slipped into the committed file. Worth pinning --target-version/--fast in the sync's black step.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

The generated sagemaker-core resources.py had two blank lines between the
import block and the module logger, which black collapses to one — failing
codestyle-doc-tests (sagemaker-core) black-check. The import block ends
with "\n\n" and LOGGER_STRING began with a leading newline, so together
they emitted the extra blank line.

- tools/constants.py: drop the leading newline from LOGGER_STRING so
  regenerated resources.py is black-clean (durable fix; prevents the next
  daily Botocore sync from reintroducing it).
- resources.py: reformat the currently-committed file to match.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 AI code review

The PR removes a leading newline from LOGGER_STRING in tools/constants.py so the code generator emits a single blank line (not two) between the import block and the module logger, and reformats the committed resources.py to match. I verified the assembly logic in resources_codegen.py: generate_imports() appends "\n\n" (line 213) and generate_logging() returns LOGGER_STRING immediately after, so the former leading "\n" produced the double blank line that black collapses. The fix is correct, minimal, and purely formatting/codegen with no functional change. Looks clean.

Reviewed commit 60ce4c8. Automated review; verify before acting.

The daily Botocore sync (aws#6520) regenerated config_schema.py and
shape_dag.py without their module docstrings, failing
codestyle-doc-tests (sagemaker-core) docstyle (pydocstyle D100: missing
docstring in public module).

- config_schema.py / shape_dag.py: restore the module docstrings.
- tools/resources_codegen.py / tools/shapes_extractor.py: emit the module
  docstring when generating these files so future daily syncs stay
  docstyle-clean (durable fix).
@rsareddy0329 rsareddy0329 changed the title fix(codegen): avoid double blank line before logger in resources.py fix(codegen): restore codestyle-doc-tests compliance after botocore sync Oct 22, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 AI code review

This PR is a codegen/formatting fix to restore codestyle-doc-tests (black-check) compliance in sagemaker-core. It drops the leading newline from LOGGER_STRING so the generator stops emitting a double blank line between the import block and logger in resources.py, and adds module docstrings to the generators for config_schema.py and shape_dag.py, updating the committed generated files to match. I verified the generator logic (generate_imports ends with \n\n, so removing LOGGER_STRING's leading \n yields exactly one blank line), confirmed the output path for config_schema.py is the top-level file edited here, and confirmed no unit tests pin these generated strings. The generator and the committed generated files stay in sync. The change is clean and correctly scoped; I found no issues worth blocking.

Reviewed commit 5df72aa. Automated review; verify before acting.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 AI code review

This PR fixes codestyle-doc-tests on the generated sagemaker-core files. It removes a leading newline from LOGGER_STRING so the import block and logger assignment in generated resources.py are separated by a single blank line (black-clean), and reformats the committed resources.py to match. It also adds module docstrings to the generated config_schema.py and shape_dag.py (and the corresponding codegen writers) — these two files are not excluded from pydocstyle's match pattern (unlike resources.py/shapes.py), so they require a D100 module docstring. I verified the pydocstyle config, the codegen flow, and that no tests pin the old generated content. The change is correct, consistent between generator and committed output, and well-scoped. No issues found.

Reviewed commit 4301369. Automated review; verify before acting.

@rsareddy0329
rsareddy0329 merged commit 200b6f5 into aws:master Oct 28, 2026
29 of 30 checks passed
gwang111 added a commit to gwang111/sagemaker-python-sdk that referenced this pull request Nov 14, 2026
* fix(codegen): restore codestyle-doc-tests compliance after botocore sync (aws#6523)

* fix(codegen): avoid double blank line before logger in resources.py

The generated sagemaker-core resources.py had two blank lines between the
import block and the module logger, which black collapses to one — failing
codestyle-doc-tests (sagemaker-core) black-check. The import block ends
with "\n\n" and LOGGER_STRING began with a leading newline, so together
they emitted the extra blank line.

- tools/constants.py: drop the leading newline from LOGGER_STRING so
  regenerated resources.py is black-clean (durable fix; prevents the next
  daily Botocore sync from reintroducing it).
- resources.py: reformat the currently-committed file to match.

* fix(codegen): restore module docstrings in config_schema and shape_dag

The daily Botocore sync (aws#6520) regenerated config_schema.py and
shape_dag.py without their module docstrings, failing
codestyle-doc-tests (sagemaker-core) docstyle (pydocstyle D100: missing
docstring in public module).

- config_schema.py / shape_dag.py: restore the module docstrings.
- tools/resources_codegen.py / tools/shapes_extractor.py: emit the module
  docstring when generating these files so future daily syncs stay
  docstyle-clean (durable fix).

---------

Co-authored-by: Roja Reddy Sareddy <rsareddy@amazon.com>

* style(data_preparer): format DataPreparer files with black

Run black 26.3.1 (the version pinned in requirements/tox) over the
DataPreparer files that black-check flags, so the codestyle check passes
on master. Formatting only: black's safe mode verified each file's AST
is unchanged, and the unit suites give identical results before and
after. No files outside this change are touched.

---
X-AI-Prompt: Make the DataPreparer port pass public master's codestyle checks
X-AI-Tool: Kiro

* test(data_preparer): keep internal names out of the redaction guard

The redaction guard listed the internal names it bans as plain regexes,
so shipping it would publish them. Store those names only as SHA-256
hashes of a normalized key: identifier names match any CamelCase or
underscore run inside one token (any case), phrases match consecutive
words. Generic patterns (Java file references, *.aws.internal
principals, account IDs, preview-era wording) stay as regexes.

All 34 cases from the previous self-tests give the same result under
the new matcher. The self-tests now exercise the matching rules with
stand-in terms patched into the hash sets, so the file names nothing
internal. Also reword an internal term in a test_preparer.py comment.

---
X-AI-Prompt: Make the DataPreparer port safe and passing for the public PR
X-AI-Tool: Kiro

* test(data_preparer): run job-submitting integ suites on scheduled CI

Mark the DataPreparer integration modules that submit jobs and wait for
them (attach, SDG happy path, DT happy path, DT operators) as
gpu_intensive, the repo's marker for tests that consume real capacity.
PR checks deselect it. The cheap modules still run on PRs: schema
validation (fails client-side before submission), stop (submit then
stop) and the env-gated short-version attach.

---
X-AI-Prompt: Make the DataPreparer port safe and passing for the public PR
X-AI-Tool: Kiro

* style(data_preparer): fix flake8 and pydocstyle findings

Fix what public master's codestyle checks flag in DataPreparer code:

- flake8: unused imports and a dead local (plus its comments about
  service internals), ambiguous names, over-long lines, a
  TYPE_CHECKING import for the Table annotation, and a duplicate
  DataPreparer key in sagemaker-core's config schema (identical values).
- pydocstyle: one-line summaries for multi-line docstrings, and
  docstrings on the concrete DQ shape extractors.
- Sphinx: fix an indentation error in the DatasetJobConfig docstring
  and the attach() Returns list, and link the schema reference page
  from the Data Preparation toctree.

No behavior change; unit suites unchanged.

---
X-AI-Prompt: Make the DataPreparer port pass public master's codestyle checks
X-AI-Tool: Kiro

* chore(data_preparer): remove KmsKeyId from SDG + DQ (aws#2347)

* chore(data_preparer): remove KmsKeyId from SDG + DQ

Drop the OutputDataConfig.KmsKeyId doc section, the stale schema
fixture entry, and swap SDG-shaped unit-test fixtures to HubName.

Ported from master-data-preparation 817c66527 (aws/sagemaker-python-sdk-staging#2347).
The golden notebook hunk is left out; notebooks follow in a separate PR.

---
X-AI-Prompt: Port the KmsKeyId removal (aws#2347) onto the public-readiness branch
X-AI-Tool: Kiro

* feat(data-preparer): default DataQualityEvaluation to 3.0.0 (aws#2365)

* feat(data-preparer): default DataQualityEvaluation to 3.0.0

Raise the DQ schema-version ceiling to 3, so an unpinned evaluate()
resolves 3.0.0 wherever the service shows it to the account and 2.0.0
where it does not. Explicit version pins still resolve as before.

Look up a DQ job's progress file only in that job's own output folder,
from its name and creation time: the 3.x layout
{S3OutputPath}/data-quality-evaluation/{JobName}/{createdAt}/, then the
2.x layout {S3OutputPath}/{JobName}-{createdAt}/. The broad listing
fallback could lock onto an earlier job that reused the name.

Move the unpinned v2-shaped DQ integ test and the DQ doc examples to the
3.0.0 shape, and read outputs through MetadataS3Uri in the tutorial.

* test(data-preparer): move the SDG-then-DQ integ test to the 3.0.0 shape

TestSDGThenDQ submits an unpinned DQ request, which now resolves 3.0.0, so it
sends Operations [default_metrics] instead of the v2 evaluation_name. The
docstring no longer assumes the v2 output-folder layout.

Ported from master-data-preparation 6fe2a49b9 (aws/sagemaker-python-sdk-staging#2365).

Its MetadataS3Uri lookup replaces this branch's paginated listing of

S3OutputPath for locating DQ records, so that listing, its constant and

its tests are removed. Formatted with black; two unused test imports

dropped.

---

X-AI-Prompt: Port the DQ 3.0.0 default (aws#2365) onto the public-readiness branch

X-AI-Tool: Kiro

* chore(data_preparer): disable DataPreparer.analyze()

Remove the public analyze() method from DataPreparer so GapAnalysis is
not exposed in this release. The implementation (_analyze_impl) and
JobCategory.GAP_ANALYSIS are kept, so re-enabling is a one-line change:
restore `analyze = _DualCallable(_analyze_impl)`.

Tests that call analyze() are skipped rather than changed, and can be
un-skipped when the method is re-enabled. The category-mismatch error
message and the module docstring no longer mention analyze().

Ported from aws/sagemaker-python-sdk-staging#2323 (29aab8050, not yet
merged there). Conflicts resolved against this branch: the preparer
module docstring keeps its one-line summary, and the integ skip marker
sits after the DQ preview assertions.

---
X-AI-Prompt: Disable GapAnalysis for the public release by porting aws#2323
X-AI-Tool: Kiro

* test(data_preparer): pin analyze() as not exposed while GapAnalysis is off

aws#2323 skips the analyze() tests but nothing fails if analyze is exposed
again by accident. Assert DataPreparer (class and instance) has no
analyze attribute, that generate/evaluate/transform/attach/stop remain,
and that the category-mismatch error no longer points callers to
analyze(). Two of the three fail with analyze exposed.

---
X-AI-Prompt: Disable GapAnalysis for the public release by porting aws#2323
X-AI-Tool: Kiro

* test(train): make SFT recipe-override integ tests recipe-proof (aws#6548)

* test(train): make SFT recipe-override integ tests recipe-proof

The canaries-v3-master (sagemaker-train) job started failing after the
JumpStart Hub SFT recipe for meta-textgeneration-llama-3-2-1b-instruct
was updated (hub content 2.17.0 / template v1.0.3): training_args
nesting was removed, max_len renamed to dataset_max_len, the default
learning_rate changed, and some validation bounds were relaxed. The SFT
recipe-override integ tests pinned the old recipe shape/values, so they
broke with no SDK or test change.

Remove the 15 structure-pinning SFT tests; their merge/override/flatten/
validation behavior is already covered Hub-independently by the pinned-
fixture unit tests in tests/unit/train/test_recipe_resolver.py. Add a
schema-agnostic llama-SFT serverless test mirroring the existing RLVR and
Nova serverless tests: keys are discovered dynamically from the live Hub
spec and overrides are asserted by value, so the test survives future
recipe/version drift. Leave the already recipe-proof suites (ModelTrainer
local-recipe, evaluator, RLVR/Nova serverless) untouched.

* test(train): assert override flows into resolved recipe, not serverless HP

The scoped CodeBuild run surfaced that asserting override flow through the
serverless-filtered hyperparameters is wrong for renamed-leaf keys (e.g.
dataset_max_len -> training_config.data.max_length): the serverless path
in _apply_recipe_to_hyperparameters filters flattened recipe leaf names
against user-provided spec names, so renamed-leaf overrides are dropped.
Assert override application against the resolved recipe (the resolver's
contract) instead, keeping the test recipe-proof and leaf-name-agnostic.

The serverless drop of renamed-leaf overrides is a separate SDK issue to
be raised with the recipe owners.

---------

Co-authored-by: rsareddy0329 <rsareddy@amazon.com>

---------

Co-authored-by: rsareddy0329 <rsareddy0329@gmail.com>
Co-authored-by: Roja Reddy Sareddy <rsareddy@amazon.com>
Co-authored-by: Prarthana Rajapurohit <90079998+prar1907@users.noreply.github.com>
Co-authored-by: Dokyung Yang <67037733+dokker19@users.noreply.github.com>
Co-authored-by: Nutan Nara <nutanara@amazon.com>
(cherry picked from commit 4b2aa3e42d1120b2a268a3bb8700561c5a4212f5)
gwang111 added a commit to gwang111/sagemaker-python-sdk that referenced this pull request Nov 14, 2026
* fix(codegen): restore codestyle-doc-tests compliance after botocore sync (aws#6523)

* fix(codegen): avoid double blank line before logger in resources.py

The generated sagemaker-core resources.py had two blank lines between the
import block and the module logger, which black collapses to one — failing
codestyle-doc-tests (sagemaker-core) black-check. The import block ends
with "\n\n" and LOGGER_STRING began with a leading newline, so together
they emitted the extra blank line.

- tools/constants.py: drop the leading newline from LOGGER_STRING so
  regenerated resources.py is black-clean (durable fix; prevents the next
  daily Botocore sync from reintroducing it).
- resources.py: reformat the currently-committed file to match.

* fix(codegen): restore module docstrings in config_schema and shape_dag

The daily Botocore sync (aws#6520) regenerated config_schema.py and
shape_dag.py without their module docstrings, failing
codestyle-doc-tests (sagemaker-core) docstyle (pydocstyle D100: missing
docstring in public module).

- config_schema.py / shape_dag.py: restore the module docstrings.
- tools/resources_codegen.py / tools/shapes_extractor.py: emit the module
  docstring when generating these files so future daily syncs stay
  docstyle-clean (durable fix).

---------

Co-authored-by: Roja Reddy Sareddy <rsareddy@amazon.com>

* style(data_preparer): format DataPreparer files with black

Run black 26.3.1 (the version pinned in requirements/tox) over the
DataPreparer files that black-check flags, so the codestyle check passes
on master. Formatting only: black's safe mode verified each file's AST
is unchanged, and the unit suites give identical results before and
after. No files outside this change are touched.

---
X-AI-Prompt: Make the DataPreparer port pass public master's codestyle checks
X-AI-Tool: Kiro

* test(data_preparer): keep internal names out of the redaction guard

The redaction guard listed the internal names it bans as plain regexes,
so shipping it would publish them. Store those names only as SHA-256
hashes of a normalized key: identifier names match any CamelCase or
underscore run inside one token (any case), phrases match consecutive
words. Generic patterns (Java file references, *.aws.internal
principals, account IDs, preview-era wording) stay as regexes.

All 34 cases from the previous self-tests give the same result under
the new matcher. The self-tests now exercise the matching rules with
stand-in terms patched into the hash sets, so the file names nothing
internal. Also reword an internal term in a test_preparer.py comment.

---
X-AI-Prompt: Make the DataPreparer port safe and passing for the public PR
X-AI-Tool: Kiro

* test(data_preparer): run job-submitting integ suites on scheduled CI

Mark the DataPreparer integration modules that submit jobs and wait for
them (attach, SDG happy path, DT happy path, DT operators) as
gpu_intensive, the repo's marker for tests that consume real capacity.
PR checks deselect it. The cheap modules still run on PRs: schema
validation (fails client-side before submission), stop (submit then
stop) and the env-gated short-version attach.

---
X-AI-Prompt: Make the DataPreparer port safe and passing for the public PR
X-AI-Tool: Kiro

* style(data_preparer): fix flake8 and pydocstyle findings

Fix what public master's codestyle checks flag in DataPreparer code:

- flake8: unused imports and a dead local (plus its comments about
  service internals), ambiguous names, over-long lines, a
  TYPE_CHECKING import for the Table annotation, and a duplicate
  DataPreparer key in sagemaker-core's config schema (identical values).
- pydocstyle: one-line summaries for multi-line docstrings, and
  docstrings on the concrete DQ shape extractors.
- Sphinx: fix an indentation error in the DatasetJobConfig docstring
  and the attach() Returns list, and link the schema reference page
  from the Data Preparation toctree.

No behavior change; unit suites unchanged.

---
X-AI-Prompt: Make the DataPreparer port pass public master's codestyle checks
X-AI-Tool: Kiro

* chore(data_preparer): remove KmsKeyId from SDG + DQ (aws#2347)

* chore(data_preparer): remove KmsKeyId from SDG + DQ

Drop the OutputDataConfig.KmsKeyId doc section, the stale schema
fixture entry, and swap SDG-shaped unit-test fixtures to HubName.

Ported from master-data-preparation 817c66527 (aws/sagemaker-python-sdk-staging#2347).
The golden notebook hunk is left out; notebooks follow in a separate PR.

---
X-AI-Prompt: Port the KmsKeyId removal (aws#2347) onto the public-readiness branch
X-AI-Tool: Kiro

* feat(data-preparer): default DataQualityEvaluation to 3.0.0 (aws#2365)

* feat(data-preparer): default DataQualityEvaluation to 3.0.0

Raise the DQ schema-version ceiling to 3, so an unpinned evaluate()
resolves 3.0.0 wherever the service shows it to the account and 2.0.0
where it does not. Explicit version pins still resolve as before.

Look up a DQ job's progress file only in that job's own output folder,
from its name and creation time: the 3.x layout
{S3OutputPath}/data-quality-evaluation/{JobName}/{createdAt}/, then the
2.x layout {S3OutputPath}/{JobName}-{createdAt}/. The broad listing
fallback could lock onto an earlier job that reused the name.

Move the unpinned v2-shaped DQ integ test and the DQ doc examples to the
3.0.0 shape, and read outputs through MetadataS3Uri in the tutorial.

* test(data-preparer): move the SDG-then-DQ integ test to the 3.0.0 shape

TestSDGThenDQ submits an unpinned DQ request, which now resolves 3.0.0, so it
sends Operations [default_metrics] instead of the v2 evaluation_name. The
docstring no longer assumes the v2 output-folder layout.

Ported from master-data-preparation 6fe2a49b9 (aws/sagemaker-python-sdk-staging#2365).

Its MetadataS3Uri lookup replaces this branch's paginated listing of

S3OutputPath for locating DQ records, so that listing, its constant and

its tests are removed. Formatted with black; two unused test imports

dropped.

---

X-AI-Prompt: Port the DQ 3.0.0 default (aws#2365) onto the public-readiness branch

X-AI-Tool: Kiro

* chore(data_preparer): disable DataPreparer.analyze()

Remove the public analyze() method from DataPreparer so GapAnalysis is
not exposed in this release. The implementation (_analyze_impl) and
JobCategory.GAP_ANALYSIS are kept, so re-enabling is a one-line change:
restore `analyze = _DualCallable(_analyze_impl)`.

Tests that call analyze() are skipped rather than changed, and can be
un-skipped when the method is re-enabled. The category-mismatch error
message and the module docstring no longer mention analyze().

Ported from aws/sagemaker-python-sdk-staging#2323 (29aab8050, not yet
merged there). Conflicts resolved against this branch: the preparer
module docstring keeps its one-line summary, and the integ skip marker
sits after the DQ preview assertions.

---
X-AI-Prompt: Disable GapAnalysis for the public release by porting aws#2323
X-AI-Tool: Kiro

* test(data_preparer): pin analyze() as not exposed while GapAnalysis is off

aws#2323 skips the analyze() tests but nothing fails if analyze is exposed
again by accident. Assert DataPreparer (class and instance) has no
analyze attribute, that generate/evaluate/transform/attach/stop remain,
and that the category-mismatch error no longer points callers to
analyze(). Two of the three fail with analyze exposed.

---
X-AI-Prompt: Disable GapAnalysis for the public release by porting aws#2323
X-AI-Tool: Kiro

* test(train): make SFT recipe-override integ tests recipe-proof (aws#6548)

* test(train): make SFT recipe-override integ tests recipe-proof

The canaries-v3-master (sagemaker-train) job started failing after the
JumpStart Hub SFT recipe for meta-textgeneration-llama-3-2-1b-instruct
was updated (hub content 2.17.0 / template v1.0.3): training_args
nesting was removed, max_len renamed to dataset_max_len, the default
learning_rate changed, and some validation bounds were relaxed. The SFT
recipe-override integ tests pinned the old recipe shape/values, so they
broke with no SDK or test change.

Remove the 15 structure-pinning SFT tests; their merge/override/flatten/
validation behavior is already covered Hub-independently by the pinned-
fixture unit tests in tests/unit/train/test_recipe_resolver.py. Add a
schema-agnostic llama-SFT serverless test mirroring the existing RLVR and
Nova serverless tests: keys are discovered dynamically from the live Hub
spec and overrides are asserted by value, so the test survives future
recipe/version drift. Leave the already recipe-proof suites (ModelTrainer
local-recipe, evaluator, RLVR/Nova serverless) untouched.

* test(train): assert override flows into resolved recipe, not serverless HP

The scoped CodeBuild run surfaced that asserting override flow through the
serverless-filtered hyperparameters is wrong for renamed-leaf keys (e.g.
dataset_max_len -> training_config.data.max_length): the serverless path
in _apply_recipe_to_hyperparameters filters flattened recipe leaf names
against user-provided spec names, so renamed-leaf overrides are dropped.
Assert override application against the resolved recipe (the resolver's
contract) instead, keeping the test recipe-proof and leaf-name-agnostic.

The serverless drop of renamed-leaf overrides is a separate SDK issue to
be raised with the recipe owners.

---------

Co-authored-by: rsareddy0329 <rsareddy@amazon.com>

---------

Co-authored-by: rsareddy0329 <rsareddy0329@gmail.com>
Co-authored-by: Roja Reddy Sareddy <rsareddy@amazon.com>
Co-authored-by: Prarthana Rajapurohit <90079998+prar1907@users.noreply.github.com>
Co-authored-by: Dokyung Yang <67037733+dokker19@users.noreply.github.com>
Co-authored-by: Nutan Nara <nutanara@amazon.com>
(cherry picked from commit 4b2aa3e42d1120b2a268a3bb8700561c5a4212f5)
gwang111 added a commit to gwang111/sagemaker-python-sdk that referenced this pull request Nov 14, 2026
…ove KmsKeyId

* fix(codegen): restore codestyle-doc-tests compliance after botocore sync (aws#6523)

* fix(codegen): avoid double blank line before logger in resources.py

The generated sagemaker-core resources.py had two blank lines between the
import block and the module logger, which black collapses to one — failing
codestyle-doc-tests (sagemaker-core) black-check. The import block ends
with "\n\n" and LOGGER_STRING began with a leading newline, so together
they emitted the extra blank line.

- tools/constants.py: drop the leading newline from LOGGER_STRING so
  regenerated resources.py is black-clean (durable fix; prevents the next
  daily Botocore sync from reintroducing it).
- resources.py: reformat the currently-committed file to match.

* fix(codegen): restore module docstrings in config_schema and shape_dag

The daily Botocore sync (aws#6520) regenerated config_schema.py and
shape_dag.py without their module docstrings, failing
codestyle-doc-tests (sagemaker-core) docstyle (pydocstyle D100: missing
docstring in public module).

- config_schema.py / shape_dag.py: restore the module docstrings.
- tools/resources_codegen.py / tools/shapes_extractor.py: emit the module
  docstring when generating these files so future daily syncs stay
  docstyle-clean (durable fix).

---------

Co-authored-by: Roja Reddy Sareddy <rsareddy@amazon.com>

* style(data_preparer): format DataPreparer files with black

Run black 26.3.1 (the version pinned in requirements/tox) over the
DataPreparer files that black-check flags, so the codestyle check passes
on master. Formatting only: black's safe mode verified each file's AST
is unchanged, and the unit suites give identical results before and
after. No files outside this change are touched.

* test(data_preparer): keep internal names out of the redaction guard

The redaction guard listed the internal names it bans as plain regexes,
so shipping it would publish them. Store those names only as SHA-256
hashes of a normalized key: identifier names match any CamelCase or
underscore run inside one token (any case), phrases match consecutive
words. Generic patterns (Java file references, internal-domain
principals, account IDs, preview-era wording) stay as regexes.

All 34 cases from the previous self-tests give the same result under
the new matcher. The self-tests now exercise the matching rules with
stand-in terms patched into the hash sets, so the file names nothing
internal. Also reword an internal term in a test_preparer.py comment.

* test(data_preparer): run job-submitting integ suites on scheduled CI

Mark the DataPreparer integration modules that submit jobs and wait for
them (attach, SDG happy path, DT happy path, DT operators) as
gpu_intensive, the repo's marker for tests that consume real capacity.
PR checks deselect it. The cheap modules still run on PRs: schema
validation (fails client-side before submission), stop (submit then
stop) and the env-gated short-version attach.

* style(data_preparer): fix flake8 and pydocstyle findings

Fix what public master's codestyle checks flag in DataPreparer code:

- flake8: unused imports and a dead local (plus its comments about
  service internals), ambiguous names, over-long lines, a
  TYPE_CHECKING import for the Table annotation, and a duplicate
  DataPreparer key in sagemaker-core's config schema (identical values).
- pydocstyle: one-line summaries for multi-line docstrings, and
  docstrings on the concrete DQ shape extractors.
- Sphinx: fix an indentation error in the DatasetJobConfig docstring
  and the attach() Returns list, and link the schema reference page
  from the Data Preparation toctree.

No behavior change; unit suites unchanged.

* chore(data_preparer): remove KmsKeyId from SDG + DQ

* chore(data_preparer): remove KmsKeyId from SDG + DQ

Drop the OutputDataConfig.KmsKeyId doc section, the stale schema
fixture entry, and swap SDG-shaped unit-test fixtures to HubName.

The golden notebook hunk is left out; notebooks follow in a separate PR.

* feat(data-preparer): default DataQualityEvaluation to 3.0.0

* feat(data-preparer): default DataQualityEvaluation to 3.0.0

Raise the DQ schema-version ceiling to 3, so an unpinned evaluate()
resolves 3.0.0 wherever the service shows it to the account and 2.0.0
where it does not. Explicit version pins still resolve as before.

Look up a DQ job's progress file only in that job's own output folder,
from its name and creation time: the 3.x layout
{S3OutputPath}/data-quality-evaluation/{JobName}/{createdAt}/, then the
2.x layout {S3OutputPath}/{JobName}-{createdAt}/. The broad listing
fallback could lock onto an earlier job that reused the name.

Move the unpinned v2-shaped DQ integ test and the DQ doc examples to the
3.0.0 shape, and read outputs through MetadataS3Uri in the tutorial.

* test(data-preparer): move the SDG-then-DQ integ test to the 3.0.0 shape

TestSDGThenDQ submits an unpinned DQ request, which now resolves 3.0.0, so it
sends Operations [default_metrics] instead of the v2 evaluation_name. The
docstring no longer assumes the v2 output-folder layout.


Its MetadataS3Uri lookup replaces this branch's paginated listing of

S3OutputPath for locating DQ records, so that listing, its constant and

its tests are removed. Formatted with black; two unused test imports

dropped.



* chore(data_preparer): disable DataPreparer.analyze()

Remove the public analyze() method from DataPreparer so GapAnalysis is
not exposed in this release. The implementation (_analyze_impl) and
JobCategory.GAP_ANALYSIS are kept, so re-enabling is a one-line change:
restore `analyze = _DualCallable(_analyze_impl)`.

Tests that call analyze() are skipped rather than changed, and can be
un-skipped when the method is re-enabled. The category-mismatch error
message and the module docstring no longer mention analyze().

merged there). Conflicts resolved against this branch: the preparer
module docstring keeps its one-line summary, and the integ skip marker
sits after the DQ preview assertions.

* test(data_preparer): pin analyze() as not exposed while GapAnalysis is off

An earlier change skips the analyze() tests but nothing fails if analyze is exposed
again by accident. Assert DataPreparer (class and instance) has no
analyze attribute, that generate/evaluate/transform/attach/stop remain,
and that the category-mismatch error no longer points callers to
analyze(). Two of the three fail with analyze exposed.

* test(train): make SFT recipe-override integ tests recipe-proof (aws#6548)

* test(train): make SFT recipe-override integ tests recipe-proof

The canaries-v3-master (sagemaker-train) job started failing after the
JumpStart Hub SFT recipe for meta-textgeneration-llama-3-2-1b-instruct
was updated (hub content 2.17.0 / template v1.0.3): training_args
nesting was removed, max_len renamed to dataset_max_len, the default
learning_rate changed, and some validation bounds were relaxed. The SFT
recipe-override integ tests pinned the old recipe shape/values, so they
broke with no SDK or test change.

Remove the 15 structure-pinning SFT tests; their merge/override/flatten/
validation behavior is already covered Hub-independently by the pinned-
fixture unit tests in tests/unit/train/test_recipe_resolver.py. Add a
schema-agnostic llama-SFT serverless test mirroring the existing RLVR and
Nova serverless tests: keys are discovered dynamically from the live Hub
spec and overrides are asserted by value, so the test survives future
recipe/version drift. Leave the already recipe-proof suites (ModelTrainer
local-recipe, evaluator, RLVR/Nova serverless) untouched.

* test(train): assert override flows into resolved recipe, not serverless HP

The scoped CodeBuild run surfaced that asserting override flow through the
serverless-filtered hyperparameters is wrong for renamed-leaf keys (e.g.
dataset_max_len -> training_config.data.max_length): the serverless path
in _apply_recipe_to_hyperparameters filters flattened recipe leaf names
against user-provided spec names, so renamed-leaf overrides are dropped.
Assert override application against the resolved recipe (the resolver's
contract) instead, keeping the test recipe-proof and leaf-name-agnostic.

The serverless drop of renamed-leaf overrides is a separate SDK issue to
be raised with the recipe owners.

---------

Co-authored-by: rsareddy0329 <rsareddy@amazon.com>

---------

Co-authored-by: rsareddy0329 <rsareddy0329@gmail.com>
Co-authored-by: Roja Reddy Sareddy <rsareddy@amazon.com>
Co-authored-by: Prarthana Rajapurohit <90079998+prar1907@users.noreply.github.com>
Co-authored-by: Dokyung Yang <67037733+dokker19@users.noreply.github.com>
Co-authored-by: Nutan Nara <nutanara@amazon.com>
papriwal pushed a commit that referenced this pull request Nov 16, 2026
…d transformation jobs (#6585)

* feat(data_preparer): add DataPreparer for data preparation jobs

* feat(data_preparer): add DataPreparer for data preparation jobs

Add DataPreparer to sagemaker-train (sagemaker.ai_registry): submit and
track SageMaker data preparation jobs from the SDK.

- SyntheticDataGeneration (generate), including typed auto-labeling
  options and the labeling summary reader
- DataQualityEvaluation (evaluate), v2 by default, v3 when pinned
- DataTransformation (transform), one operator per job
- attach() to re-attach to a job, stop() to cancel one, wait=False
  Job handles, live status panel and optional log tailing
- Job config validated against the service's published job schemas
- DataSet.create targets any hub and writes v5 hub content documents
- PipelineSession capture for use as a pipeline step
- Telemetry: DATA_PREPARATION feature (22) and the job ARN on success
  and failure
- sagemaker config: DataPreparer defaults section
- Docs: quickstart, configuration, SDG / DQ / DT tutorials, API
  reference; three example notebooks

* docs(data_preparer): correct Job resource and enum docstrings

The _get_job_resource docstring said the generated
sagemaker.core.resources.Job lacks job_arn; it no longer does. Describe
what the local Job adds (progress panel, log streaming, sample counting,
labeling summary) instead.

The constants module told maintainers to delete the local JobCategory /
JobStatus enums once sagemaker-core is regenerated. Doing so would drop
the DataPreparer categories, which the public service model's
JobCategory enum does not list. State why they stay local.

* fix(ai_registry): write DatasetS3Uri in DataSet.create documents

DataSet.create() wrote DatasetS3Bucket and DatasetS3Prefix on v3/v4/v5
hub content documents but not DatasetS3Uri, the location key
DataTransformation writes on its own output documents and the one
DataSet.get reads first. Write it, set to the same object.

Add an integration test that runs DataTransformation on a dataset
registered with DataSet.create() (document schema 4.0.0 and 5.0.0, Custom
format), the bring-your-own-data path the DT tutorial documents. It
passes live in us-west-2. The direct-import fixture's docstring claimed
create() datasets fail DT; that does not reproduce (create() also writes
DatasetType), so it now states why the fixture imports directly.

Raised by the PR review bot on .

* docs(data_preparer): use the nested job-config shape in examples

docs/training/data_preparer.rst and the DatasetJobConfig docstring used
flat keywords (num_requested_samples, spec_s3_uri, dataset_arn) that the
published v2 schemas reject (GenerationConfig / InputDataConfig: Field
required). Rewrite them to the nested shape the quickstart and tutorials
use; every example on these pages now validates against the live
us-west-2 schemas. Fix a leftover spec_s3_uri reference in the
quickstart text.

Add a unit test that fails if the retired flat keywords reappear in the
DataPreparer docs or docstrings.

Raised by the PR review bot on .

* chore: hold back the DataPreparer example notebooks

Two of the three notebooks use the flat job-config keywords the v2
schemas reject, and the golden notebook still needs cleanup. Ship the
notebooks in a follow-up once all of them are fixed and run end to end.

* change(data_preparer): default DataQualityEvaluation to 3.0.0 and remove KmsKeyId

* fix(codegen): restore codestyle-doc-tests compliance after botocore sync (#6523)

* fix(codegen): avoid double blank line before logger in resources.py

The generated sagemaker-core resources.py had two blank lines between the
import block and the module logger, which black collapses to one — failing
codestyle-doc-tests (sagemaker-core) black-check. The import block ends
with "\n\n" and LOGGER_STRING began with a leading newline, so together
they emitted the extra blank line.

- tools/constants.py: drop the leading newline from LOGGER_STRING so
  regenerated resources.py is black-clean (durable fix; prevents the next
  daily Botocore sync from reintroducing it).
- resources.py: reformat the currently-committed file to match.

* fix(codegen): restore module docstrings in config_schema and shape_dag

The daily Botocore sync (#6520) regenerated config_schema.py and
shape_dag.py without their module docstrings, failing
codestyle-doc-tests (sagemaker-core) docstyle (pydocstyle D100: missing
docstring in public module).

- config_schema.py / shape_dag.py: restore the module docstrings.
- tools/resources_codegen.py / tools/shapes_extractor.py: emit the module
  docstring when generating these files so future daily syncs stay
  docstyle-clean (durable fix).

---------

Co-authored-by: Roja Reddy Sareddy <rsareddy@amazon.com>

* style(data_preparer): format DataPreparer files with black

Run black 26.3.1 (the version pinned in requirements/tox) over the
DataPreparer files that black-check flags, so the codestyle check passes
on master. Formatting only: black's safe mode verified each file's AST
is unchanged, and the unit suites give identical results before and
after. No files outside this change are touched.

* test(data_preparer): keep internal names out of the redaction guard

The redaction guard listed the internal names it bans as plain regexes,
so shipping it would publish them. Store those names only as SHA-256
hashes of a normalized key: identifier names match any CamelCase or
underscore run inside one token (any case), phrases match consecutive
words. Generic patterns (Java file references, internal-domain
principals, account IDs, preview-era wording) stay as regexes.

All 34 cases from the previous self-tests give the same result under
the new matcher. The self-tests now exercise the matching rules with
stand-in terms patched into the hash sets, so the file names nothing
internal. Also reword an internal term in a test_preparer.py comment.

* test(data_preparer): run job-submitting integ suites on scheduled CI

Mark the DataPreparer integration modules that submit jobs and wait for
them (attach, SDG happy path, DT happy path, DT operators) as
gpu_intensive, the repo's marker for tests that consume real capacity.
PR checks deselect it. The cheap modules still run on PRs: schema
validation (fails client-side before submission), stop (submit then
stop) and the env-gated short-version attach.

* style(data_preparer): fix flake8 and pydocstyle findings

Fix what public master's codestyle checks flag in DataPreparer code:

- flake8: unused imports and a dead local (plus its comments about
  service internals), ambiguous names, over-long lines, a
  TYPE_CHECKING import for the Table annotation, and a duplicate
  DataPreparer key in sagemaker-core's config schema (identical values).
- pydocstyle: one-line summaries for multi-line docstrings, and
  docstrings on the concrete DQ shape extractors.
- Sphinx: fix an indentation error in the DatasetJobConfig docstring
  and the attach() Returns list, and link the schema reference page
  from the Data Preparation toctree.

No behavior change; unit suites unchanged.

* chore(data_preparer): remove KmsKeyId from SDG + DQ

* chore(data_preparer): remove KmsKeyId from SDG + DQ

Drop the OutputDataConfig.KmsKeyId doc section, the stale schema
fixture entry, and swap SDG-shaped unit-test fixtures to HubName.

The golden notebook hunk is left out; notebooks follow in a separate PR.

* feat(data-preparer): default DataQualityEvaluation to 3.0.0

* feat(data-preparer): default DataQualityEvaluation to 3.0.0

Raise the DQ schema-version ceiling to 3, so an unpinned evaluate()
resolves 3.0.0 wherever the service shows it to the account and 2.0.0
where it does not. Explicit version pins still resolve as before.

Look up a DQ job's progress file only in that job's own output folder,
from its name and creation time: the 3.x layout
{S3OutputPath}/data-quality-evaluation/{JobName}/{createdAt}/, then the
2.x layout {S3OutputPath}/{JobName}-{createdAt}/. The broad listing
fallback could lock onto an earlier job that reused the name.

Move the unpinned v2-shaped DQ integ test and the DQ doc examples to the
3.0.0 shape, and read outputs through MetadataS3Uri in the tutorial.

* test(data-preparer): move the SDG-then-DQ integ test to the 3.0.0 shape

TestSDGThenDQ submits an unpinned DQ request, which now resolves 3.0.0, so it
sends Operations [default_metrics] instead of the v2 evaluation_name. The
docstring no longer assumes the v2 output-folder layout.


Its MetadataS3Uri lookup replaces this branch's paginated listing of

S3OutputPath for locating DQ records, so that listing, its constant and

its tests are removed. Formatted with black; two unused test imports

dropped.



* chore(data_preparer): disable DataPreparer.analyze()

Remove the public analyze() method from DataPreparer so GapAnalysis is
not exposed in this release. The implementation (_analyze_impl) and
JobCategory.GAP_ANALYSIS are kept, so re-enabling is a one-line change:
restore `analyze = _DualCallable(_analyze_impl)`.

Tests that call analyze() are skipped rather than changed, and can be
un-skipped when the method is re-enabled. The category-mismatch error
message and the module docstring no longer mention analyze().

merged there). Conflicts resolved against this branch: the preparer
module docstring keeps its one-line summary, and the integ skip marker
sits after the DQ preview assertions.

* test(data_preparer): pin analyze() as not exposed while GapAnalysis is off

An earlier change skips the analyze() tests but nothing fails if analyze is exposed
again by accident. Assert DataPreparer (class and instance) has no
analyze attribute, that generate/evaluate/transform/attach/stop remain,
and that the category-mismatch error no longer points callers to
analyze(). Two of the three fail with analyze exposed.

* test(train): make SFT recipe-override integ tests recipe-proof (#6548)

* test(train): make SFT recipe-override integ tests recipe-proof

The canaries-v3-master (sagemaker-train) job started failing after the
JumpStart Hub SFT recipe for meta-textgeneration-llama-3-2-1b-instruct
was updated (hub content 2.17.0 / template v1.0.3): training_args
nesting was removed, max_len renamed to dataset_max_len, the default
learning_rate changed, and some validation bounds were relaxed. The SFT
recipe-override integ tests pinned the old recipe shape/values, so they
broke with no SDK or test change.

Remove the 15 structure-pinning SFT tests; their merge/override/flatten/
validation behavior is already covered Hub-independently by the pinned-
fixture unit tests in tests/unit/train/test_recipe_resolver.py. Add a
schema-agnostic llama-SFT serverless test mirroring the existing RLVR and
Nova serverless tests: keys are discovered dynamically from the live Hub
spec and overrides are asserted by value, so the test survives future
recipe/version drift. Leave the already recipe-proof suites (ModelTrainer
local-recipe, evaluator, RLVR/Nova serverless) untouched.

* test(train): assert override flows into resolved recipe, not serverless HP

The scoped CodeBuild run surfaced that asserting override flow through the
serverless-filtered hyperparameters is wrong for renamed-leaf keys (e.g.
dataset_max_len -> training_config.data.max_length): the serverless path
in _apply_recipe_to_hyperparameters filters flattened recipe leaf names
against user-provided spec names, so renamed-leaf overrides are dropped.
Assert override application against the resolved recipe (the resolver's
contract) instead, keeping the test recipe-proof and leaf-name-agnostic.

The serverless drop of renamed-leaf overrides is a separate SDK issue to
be raised with the recipe owners.

---------

Co-authored-by: rsareddy0329 <rsareddy@amazon.com>

---------

Co-authored-by: rsareddy0329 <rsareddy0329@gmail.com>
Co-authored-by: Roja Reddy Sareddy <rsareddy@amazon.com>
Co-authored-by: Prarthana Rajapurohit <90079998+prar1907@users.noreply.github.com>
Co-authored-by: Dokyung Yang <67037733+dokker19@users.noreply.github.com>
Co-authored-by: Nutan Nara <nutanara@amazon.com>

* chore(data_preparer): remove the GapAnalysis job category

Builds on earlier work by Nutan Nara, which hid DataPreparer.analyze() but kept
the GapAnalysis code for a one-line re-enable. The package source and
repo are public, so remove it entirely for this release:

- preparer.py: _analyze_impl, the GapAnalysis branches in attach() and
  _run, the re-enable comment, and the attach() docstring mention.
- constants.py: JobCategory.GAP_ANALYSIS and its schema-version ceiling.
- sagemaker-core telemetry: the RecommendationResult ARN mapping.
- tests: test_analyze.py, the GapAnalysis test in test_preparer.py and the
  integ test_03_analyze_gaps (and its env vars); the empty-output test
  now uses an unrecognized category string.

attach() now rejects a job ARN whose category DataPreparer does not
support with a ValueError listing the supported ones, before any
service call; previously it reached DescribeJob and then failed on
the enum lookup. The redaction guard bans the GapAnalysis names
(hashed) and now also scans the DataPreparer unit tests for hashed
internal names.

* feat(ai_registry): typed Confidence, Optimizer and Review labeling options

* feat(ai_registry): typed Confidence, Optimizer and Review labeling options

Add the three opt-in Config objects the auto-labeling service accepts on
labeling.classification as typed shapes beside the existing options:
Confidence {Method, Estimator, Models, Recalibration, FloorBypass},
Optimizer {Mode, TeacherModel, Seed, Parser, Elicitation} and Review
{LabelField, Scope, PredictionsS3Uris, RulesS3Uri, JudgeModels,
JudgeScope, MaxJudgeRows, EstimateOnly}, plus the JudgeModel entry they
share. Only ClassificationLabelingOptions carries them, matching the
service's CONFIDENCE/OPTIMIZER/REVIEW_LABELING_TYPES, and a Review
refuses the fields that shape a labeling run (demos, routing,
evaluation_data, scoring, confidence, optimizer), as CreateJob does.

Wire keys come from the alias generator; value sets and bounds stay the
service's to enforce. A request that sets none of the new fields
serializes exactly as before.

Tests: field-by-field wire assertions, per-task acceptance, the Review
exclusions, and a fixture parity suite that pins to_dataset_options()
against 19 request documents captured from a hand-built client (every
task, demos + gold, routed corpus run, graders, and each opt-in), so a
caller switching from the raw dict to these classes sends the same bytes.


* test(ai_registry): integ test for a typed auto-labeling job

Add the first integration test for auto-labeling through the SDK: one
classification job over a 10-row banking-intents fixture (the rows are
also the gold) with the opt-in Confidence object set, waited on, and
read back through LabelingSummary.from_dataset. Asserts the request's
wire shape, the summary's type, counts, accuracy range, juror list and
DataSet ARNs, and that the labels file the index names carries one row
per input with a label from the spec's Label Set and a verbalized
confidence score.

Same role, bucket and hub knobs as the DataTransformation tests
(DATA_PREPARER_INTEG_ROLE_ARN; test_role would hand the job the
caller's role, which does not trust sagemaker.amazonaws.com). Marked
gpu_intensive like the other job-running integ tests.

Passed against the beta service in 3m22s.

* feat(data_preparer): auto-labeling client operators (data_preparer/operators)

* feat(data_preparer): operators package with the result contract and common primitives

Start the port of the auto-labeling client scripts into
data_preparer/operators/, following the two-job method: each script is
functionalized (parameters in, typed result out, refusals as exceptions,
no file writes, no process exit) and then moved.

This commit lands the contract and the primitives everything else builds on:

- _result: OperatorResult (pydantic, to_json) and run_log_event; events are
  returned in the result for the caller to append, never written.
- exceptions: DataPreparerOperatorError, the refusal base (also a ValueError).
- common/rows: JSONL reading, the S3 head peek and streamed read, the
  client-read notice on a dedicated logger instead of stderr.
- common/metrics: macro-F1 parts, multiset micro-F1, token F1, ranks,
  Pearson/Spearman, quadratic weighted kappa.
- common/bounds: calibration_sample_size and the zero-error bound.
- common/selection: select_with_floor and heldout_review_flag.
- generate/correctness: the job's per-task row rule (task_correct) and
  the task field tables.

Unit tests in the SDK layout; function-level parity with the skill's
originals verified on randomized inputs.


* feat(data_preparer): labeling field contract, local scorer and spec selection operators

- generate/fields: the row and field contract (reserved, blind and hidden
  fields, review tags, side files, people-labeled provenance).
- generate/scoring: score() over every task with a typed ScoreResult;
  counts carry correct/total for every task so a bound can be composed.
- generate/spec_select: select() with a typed SpecDecision; the deprecated
  'iterations' alias is reported in result.warnings instead of stderr.
- _result: results carry warnings beside events.

Structural parity with the skill's scoring.py and select_best_spec.py on
randomized inputs, including refusal messages.


* feat(data_preparer): split_state operator, the frozen seed-split guard

transform/split_state: freeze, verify, guard_read, rehash and relabel as
functions. Nothing writes a file: freeze/rehash/relabel return the rows
and the state document for the caller to write, with hashes over the
exact bytes rows_bytes serializes; a test read comes back as a run-log
event in the result instead of being appended.

Lockstep parity with the skill's split_state.py on 120 random projects
(files, state, run-log entries and every refusal message identical).


* feat(data_preparer): kfold and demos operators

- transform/kfold: stratified_folds and build_kfold, returning every fold
  and rotation file's rows plus the manifest (hashes over those bytes).
- generate/demos: fixed_demos, fixed_demos_ner and select_demos.

Parity: folds and demos equal the skill's on randomized rows; the files
and manifest build_kfold returns are byte-identical to kfold_rotate.py's
CLI output on random seeds.


* feat(data_preparer): rubric operator (anchored-rubric levels, anchors, gaps)

generate/rubric: scale_levels / is_banded / score_levels, select_rubric_anchors,
rubric_gaps and rubric_warning, moved as they were with refusals as
DataPreparerOperatorError and docstrings to the operator bar. Parity with the
skill's rubric.py on randomized scales, rows and specs.


* feat(data_preparer): detect_task operator (B8, task-type detection)

generate/detect_task.detect returns a typed TaskDetection from the spec and a
sample of the labeled seed; the CLI's file reads and client-read notice stay
with the caller. Parity with detect_task_type.detect on 400 randomized specs
and samples.


* feat(data_preparer): inspect_input operator (B8, first-row inventory)

generate/inspect_input.inspect returns a typed InspectReport from one row of
the corpus and the seed (local, s3:// object or folder, .gz, or a DataSet ARN
through an injectable resolver). Parity with inspect_input.py on randomized
local files and stubbed S3 objects, including every refusal message.


* feat(data_preparer): taxonomy_gate operator (B8, pre-spend taxonomy check)

generate/taxonomy_gate.gate returns a typed TaxonomyReport: the Label Set
parse, absence-defined classes, seed coverage and the overlap check
(sentence-transformers when installed, lexical Jaccard otherwise, the method
reported). Parity with taxonomy_gate.py on 300 randomized specs and seeds.


* feat(data_preparer): induce_spec operator and the Bedrock Converse client

- common/bedrock: make_client / invoke / rejects_temperature, moved as they
  were (retries in one place, deterministic backoff).
- generate/induce_spec: the three rule-writer prompts unchanged byte for
  byte, plus induce_spec() carrying the CLI's flow (filters, deterministic
  order, thin-evidence warnings, refusals) with the model call injectable.

Parity: prompts identical on randomized rows; the CLI's output, warnings
and refusals equal the operator's with a stubbed model.


* test(data_preparer): unit tests for the induce_spec and bedrock operators


* fix(data_preparer): score() normalizes label_map keys itself

A caller-supplied map with cased or padded keys ranked nothing and raised
the no-rank-mapping refusal; the keys are now lower-cased and stripped at
the point of use, as the CLI's map builder already did.


* feat(data_preparer): labeling_request and job_client operators (ex engine/sdg_backend)

- generate/labeling_request: the task contract tables, spec_score_scale,
  build_labeling_request (the client-side checks, unchanged) and
  to_dataset_job_config, which hands DataPreparer a DatasetJobConfig with
  the typed *LabelingOptions shapes (labeling_options_from_document maps
  the document back onto them).
- generate/job_client: S3 transfer, submit with retry / re-attach and the
  refusal classes (CreateJobRefused, OptionRefused,
  LabelingBackendUnavailable, JobWaitError), read_job_results through
  LabelingSummary, and the Hub helpers.

Parity: documents, refusal messages, summaries and helpers equal the
skill's on the 19 PR-1 fixtures and 600 randomized requests; the typed
shapes reproduce every document's DatasetOptions.


* feat(data_preparer): hub operator (ex hub_io)

Port the skill's hub_io.py into operators/generate/hub.py: the resolve
door (local path, s3:// URI or DataSet ARN to the object the pipeline
reads, stopping at the URI with ETag and size unless a download is
asked for), the register door (per-run S3 prefix, lineage guard and
append consent before any upload, v4-only document, Hub failure
degrades after the uploads), the dataset-transformation doors (dt-view,
register-output, promote, import-s3) and the scratch cleanup.

The run log is a seam, not a dependency: scratch_event returns the
entry a caller appends, scratch_entries and scratch_cleanup take the
project's entries, and the cleanup returns a ScratchResult whose events
carry the deletion record. corpus_ref_document builds the pointer the
CLI writes. Refusals are DataPreparerOperatorError with the skill's
messages; stderr notes go to the module logger. Client factories stay
module-level so tests stub them. inspect_input's default ARN resolver
now imports a module that exists.


* feat(data_preparer): run_context and run_records operators

Port engine/run_context.py (run-id sanitizing, the run-scoped staging
directory and S3 prefix, and the best-effort pruning of idle staging
scopes that keeps each stage's job.json) into common/run_context.py
unchanged in behavior.

Port io_utils' run-log record of a labeling run into
generate/run_records.py with the run log as a seam: labeling_run_record
returns the job entries and the artifact entry for the caller's writer
(the artifact's job_entries are the ids the writer hands back), and
read_labeling_runs, latest_labeling_runs, labeling_run_invocation and
labeling_run_for_output take the project's entries and root instead of
reading the file. The entries hold no value twice, as before.


* feat(data_preparer): label_decisions operator (ex labelcheck/lc_decide)

Port labelcheck/lc_decide.py (the decisions on a label review's
contradiction list: cell escaping, label canon, item sha, overrides,
decisions.csv, the logged decisions, spec iteration names and the pure
apply_decisions) and the decision-handling pieces of
apply_label_decisions.py main() (the merge of logged and CSV decisions
with the item-version check, the test rows a decision would touch, the
default label set, the new-or-changed decision entries, the dry-run
summary) into generate/label_decisions.py. The run log is a seam: the
logged decisions take the project's entries and the decision entries
come back for the caller's writer. Writing the files and the split
relabel stay with the caller.


* feat(data_preparer): label_review operator (ex review_labels)

Port the decisions review_labels.py makes around its review-only
CreateJob into generate/label_review.py: the client checks on the
arguments and on the rows to send (the frozen split's test rows, stale
gold, the job's row limits), Config.Review, the seed text the job reads,
the content and request digests a re-attach compares, the unused
approval a judged job needs, the run-log entries of a run, the checks on
the job's summary.json, the decisions.csv rows the seed scope leaves for
the user and the result the client reports. review_folder is the one S3
call. Uploading, submitting, the job record and the split guard stay
with the caller. Also a black reformat left over in test_hub.py.


* feat(data_preparer): adopt_pick operator (ex adopt_job_pick)

Port adopt_job_pick.py into generate/adopt_pick.py: the check that the
pick's folder is complete, the approval that must name the pick's
sha256 and job, the decision.json document and the decision entry an
adoption leaves, and the re-check before shipping that the spec's bytes
are still the approved pick. The run-log entries come in as a parameter
and the decision entry goes back in the result's events; copying the
pick and writing decision.json stay with the caller.


* feat(data_preparer): review_export and cold_start operators (ex bootstrap_seed, part 1)

Port the export parsers of bootstrap_seed.py (provenance values, the
Label Studio task flattening, the one-decided-label-per-id fold with its
reviewers, conflicts and unresolved rows, and the order-insensitive
label comparisons) into transform/review_export.py as public functions,
and the cold-start sample (sample size by target, the certificate
warning, draw_sample) into transform/cold_start.py. Refusals are
DataPreparerOperatorError with the skill's messages.


* feat(data_preparer): seed operator (ex bootstrap_seed, part 2)

Port the non-HIL half of bootstrap_seed.py into transform/seed.py: the
seed append check (the same fold again is a no-op, a different review of
the same rows is refused), merge_seed_labels (the people's labels onto
the labeled rows, the model's answer moved aside), the review-set drop of
rows people labeled already with the scoring of the spot-check rows among
them, the overlay (provenance rule, seed files under their own gold
field, build_overlay, the CodeGen instruction and the hand-off record),
review_verdict and fill_missing_ids. Rows in, rows and reports out; the
caller reads and writes the files. The HIL fold (assemble_hil_seed,
check_fold, the spot-check verdict) stays in the skill.


* feat(data_preparer): golden_review operator

Port golden_review.py into generate/golden_review.py: route (the flagged
golden rows as a blind review file and the manifest), apply (the person's
export folded into the reviewed copy; a relabeled row leaves the
certificate's rows) and check_reviewed (everything derived again from the
inputs; any change a person did not make is refused). The functions read
the files they are given and return the review rows, the copy's text and
the manifest for the caller to write; the split guard's test-read entry
comes back in events. Refusals are GoldenReviewError with the skill's
messages.


* feat(data_preparer): labeling_round operator (ex run_indexed_labeling helpers)

Port the helpers of run_indexed_labeling.py (lines before main) into
generate/labeling_round.py: the run id check, the input's form, the
local reads, the seed evidence and the no-seed message, the gold rows
split from their inputs and checked against the label set (the warning
is returned, the refusal raised), the row-id rules, the demos, the job's
labels in the skill's shape, the jurors' shortfall, the held-out report
from the job's summary, the run's record for the run log and the
re-attach digest. The orchestration in main() follows as the next step.


* fix(data_preparer): golden_review check keeps its test read on refusal

check_reviewed reads the frozen test split (a test-read run-log entry)
before its row checks. The skill logs that read at once, so a later
refusal (routed.jsonl changed, an edited manifest, a dropped or
relabeled row) leaves the read in the run log. The port kept the entry
in a local list and lost it when the check raised.

The checks after the read move into _check_read_rows; an error raised
there carries the read's entries in an `events` attribute, for the
caller to append before it reports the refusal. Results and refusal
messages are unchanged. Found by the run_round parity harness
(golden review, routed.jsonl edited after apply).


* feat(data_preparer): run_round operator (ex run_indexed_labeling main)

The orchestration of the skill's run_indexed_labeling.py main() moves
into generate/run_round.py, split where a caller writes between steps:
prepare_round (argument checks, task resolution, the client reads, the
frozen-split guard, gold and demos, the request document and the
re-attach digest; nothing uploaded), submit_round (re-attach or the
dataset-name check, the uploads, submit_labeling_job), read_round
(read_job_results, the labels, held-out report, juror shortfall, side
files, deliverable, run record and summary) and round_summary (the
summary with the run-log entry id in the command line's key order).
The helpers main() used that took args or exited are ported beside
them: resolve_task, optimizer_config, check_option_flags, split_reads,
fit_rows_in_corpus, option_gold, guard_split_reads,
check_golden_review, default_run_id. Argparse stays in the skill.

The seams, as in the other operators:
- sys.exit(msg) -> DataPreparerOperatorError(msg), text unchanged;
  RoundRefused (a subclass) carries the test reads and notes made
  before a prepare refusal, which the skill had already logged and
  printed.
- stderr WARNING/NOTE lines -> `warnings`, each line as printed, so a
  caller reproduces stderr and its order; client reads -> the
  client_read logger.
- run-log writes -> events (test reads via split_state's
  test_read_event) and a LabelingRunRecord from labeling_run_record.
- args -> explicit keyword parameters (the command line's values as
  given, which the invocation records); file writes -> returned
  request text, job-record text (on_submit, with on_refused for its
  removal), texts / copies / removes. Folder creation and run-scope
  pruning are the caller's after prepare_round.
- backend calls -> generate/job_client, looked up at call time so
  tests can stub them; except RuntimeError becomes
  except (JobWaitError, RuntimeError), and SdgApiUnavailable has no
  SDK counterpart.


* chore(data_preparer): operators package layout, exports and API reference

test_package_layout.py lists every operator module, imports each one,
checks the list against the modules on disk, and checks that the four
operator packages export nothing.

The operator __init__ files stay docstring-only, now with real
docstrings that list their modules. The operators and their tests import
modules explicitly and stub module-level seams; a flat re-export would
put 332 public names in one namespace, two of which collide
(split_s3_uri, sha256_text), and would import every module on first use.

docs/data_preparation/api_reference.rst gains an Operators section, one
automodule per module (common, generate, transform). Two Returns:
docstrings (job_client.read_job_results, label_decisions.logged_decisions)
are reworded so napoleon no longer splits them on a colon, which Sphinx
reported as an unterminated inline literal. No code changes.


* fix(data_preparer): Resolve run_round's region up front

prepare_round(region=None) passed None on to existing_datasets, whose
hub name then hashed "AiRegistry-None-<account>": a hub that does not
exist, so every DataSet name read as free and a corpus run could append
to an existing DataSet. The skill's command line always had a region
(AWS_REGION, else us-west-2).

prepare_round now resolves None to the ambient boto3 region, else
us-west-2, through job_client.resolve_region (the rule
_region_bound_session already used, now shared), so the plan, the
invocation, the job, the deliverable and the name check all carry the
resolved region.


* fix(data_preparer): Make the job errors RuntimeErrors again

CreateJobRefused, LabelingBackendUnavailable and JobWaitError (and
OptionRefused through CreateJobRefused) extended DataPreparerError
only. The skill's were RuntimeErrors, so a caller that pastes the
skill's "except RuntimeError" would miss them. They now subclass
(DataPreparerError, RuntimeError), as DataPreparerOperatorError
already pairs DataPreparerError with ValueError.

submit_round's wait clause becomes the skill's "except RuntimeError",
which now covers JobWaitError.


* fix(data_preparer): Write documents in the skill's key order

The parity harness compared dicts with ==, which ignores key order,
so files a shim writes from these results could differ in bytes from
the skill's. With the comparisons made order-sensitive, three
differences showed up; values are unchanged.

- ScoreResult (score.json): fields declared in the order the skill
  lists them for every task (exact_match, accuracy, precision, recall,
  breakdown, confusion_pairs before counts and n_no_ground_truth).
- SpecDecision (decision.json): fields declared in the skill's order;
  to_json keeps spec and shipped_spec_file in place and, when no
  refined spec was picked, puts per_type_tol before reason as the
  skill does.
- LabelingRunRecord: artifact_entry(ids) returns the artifact entry
  with job_entries right after labeling_run, where the skill's
  record_labeling_run puts it; run_round documents it as the way to
  append the record.


* refactor(data_preparer): Keep one telemetry attribution helper

_set_telemetry_attribution was defined in both common/bedrock.py and
generate/job_client.py. The one definition now lives in bedrock.py
(where the skill's bedrock_client.py had it) and job_client imports it.
Behavior is unchanged: the Bedrock client, the region-bound session and
submit_labeling_job still set it before their first call, and each of
those docstrings now says it tags the process as the SageMaker agent
plugin.


* docs(data_preparer): Document the result contract, export its error

The API reference's Operators section now documents
operators._result (OperatorResult and run_log_event), the result
contract every operator and caller uses.

DataPreparerOperatorError, the refusal every operator raises, is now
exported beside the other exceptions from data_preparer and, like
them, from sagemaker.ai_registry; test_package_layout lists it in
PUBLIC_NAMES.


* refactor(data_preparer): Untangle duplicate helper names

- label_review.sha256_text becomes sha256_hex: it takes str or bytes
  and never None, unlike labeling_round.sha256_text (None -> None, the
  skill's _sha256_text), which keeps its name.
- inspect_input drops its private _s3_split for job_client.split_s3_uri:
  both return the same (bucket, key), or raise the same error, for every
  string (checked over 2,247 S3 and non-S3 shapes); the module passes
  only s3:// strings.
- split_state.test_read_event and test_ids keep the skill's names and
  get __test__ = False, so a star import into a test module does not
  make pytest collect them.


* fix(data_preparer): Keep customer rows out of RoundPlan.to_json

RoundPlan carries the round's input rows, gold rows, demos, spec and
request text for submit_round. Its inherited to_json() would have
serialized all of them, so a caller that logged or saved a plan would
copy customer content. RoundPlan.to_json() now drops
CUSTOMER_CONTENT_FIELDS (input_rows_text, gold_rows, gold_text,
demos_text, spec_text, request_text); the attributes are unchanged and
the class docstring says so.


* fix(data_preparer): Keep labels and val scores as the data has them

ScoreResult.breakdown was typed Dict[str, float], so a data set whose
class labels are ints or bools (a 0/1 or true/false label set) failed
validation where the skill's scoring.py scored it. The keys now accept
str, int and bool, and to_json() keeps them as-is so json.dumps writes
the same keys the skill's score.json has ("1", "true"); pydantic's JSON
mode would have written the bool as "True".

SpecDecision's val, initial_val, best_refined_val, gain and per_type_tol
were float, so a candidates file with "val": 1 came back as 1.0 in
decision.json. They now accept int or float and keep what was passed.

Both were found by the skill shim: its tests feed int labels and vals
and compare the written files byte for byte.


* fix(data_preparer): Cap client-side reads in rows.read_input_rows

The skill's read_input_rows refused a file over 50 MiB before reading a
row (its rule 16: larger data is read in a job, not on the client); the
port dropped the check. CLIENT_READ_MAX_BYTES and the refusal are back:
a local file is sized with os.path.getsize, an S3 object from its
ContentLength, and a refused S3 body is closed. The refusal is a
DataPreparerOperatorError.


* fix(data_preparer): Print client-read notices to the current stderr

print_client_reads() with no stream bound its handler to the sys.stderr
object of attach time. A caller that later redirected stderr (a test
capturing output, a wrapper) saw no notices there, and once that first
object was closed every later notice printed a "Logging error"
traceback. The default handler now resolves sys.stderr per record.


* refactor(data_preparer): Group the operators by primitive: common and auto_labeling

operators/generate and operators/transform both held auto-labeling code
(the labeling job and the steps around it; the seed it learns from), and
the folder names read as the DataPreparer verbs, which neither the
generate nor the transform job calls. They merge into
operators/auto_labeling, beside the existing data_preparer/auto_labeling
shapes and summary, so the request shapes, the result model and the
operators read as one primitive. operators/common keeps what has no
labeling vocabulary and another primitive can call as it is (rows,
bounds, metrics, selection, run_context, bedrock).

Import paths change; nothing else does. The layout test, the package
docstrings and the API reference follow.


* refactor(data_preparer): Split hub.py four ways and keep one S3 helper

hub.py held four things: DataSet ARN resolution and labeled-output
registration, the scratch-version lifecycle, the dataset-transformation
handoff, and S3 transfer. They are now register.py, _scratch.py,
dt_handoff.py and _s3.py. The byte transfers and the s3:// URI split,
which job_client.py, hub.py and rows.py each defined, exist once in
_s3.py; every caller reaches its clients through the module so a test
stubs one place.

The hub-content ARN parser delegates to sagemaker-core's shared parser
instead of its own regex; a version-less ARN is read with an empty
version appended, since the shared regex expects the segment. The hub
helpers job_client.py carried (hub name, existing datasets, version
delete) live with the registration code they serve, so job_client.py
is the job: submit, re-attach, read back.

Step 2 of the per-primitive restructure (Pippin J9c9wKPhJ8QD0C).


* refactor(data_preparer): One SHA-256 and one canonical JSON form

Five modules each defined a SHA-256 helper (adopt_pick, label_review,
labeling_round, split_state twice) and five spelled their own canonical
JSON; _digest.py holds one of each. Every recorded digest keeps the
byte form it was first written with: canonical_json/sha256_json take
``ascii`` where a caller used json.dumps's ensure_ascii default, so a
re-attach still matches the digest a run recorded.

Step 3a of the per-primitive restructure (Pippin J9c9wKPhJ8QD0C).


* refactor(data_preparer): One folder per primitive, layer second

operators/{common,auto_labeling}/ becomes auto_labeling/operators/, so
the labeling primitive owns its shapes and its operators in one folder,
and the operators sit in six subsystems by the question each answers:
inspect, seed, spec, job, score, review. The eleven modules that define
no operator are _-prefixed and private to the primitive; common/ is
gone, each of its six modules moved to its one caller's subsystem.
labeling_round.py, run_round's private half, is job/_round_parts.py.

OperatorResult and its three rules move to data_preparer/
_operator_result.py, the one thing every primitive shares from day one;
run_log_event stays private to labeling as _run_log.py, since its entry
kinds are the skill project's log format. A layout test asserts no
primitive imports another and no common/ folder returns.

Imports are rewritten mechanically (module names keep their old alias
where a module is referenced as a namespace); no behaviour changes.

Step 4 of the per-primitive restructure (Pippin J9c9wKPhJ8QD0C).


* docs(data_preparer): Export the operators by name and document each one

Each subsystem lists its operators in __all__ (32 in all: inspect 3,
seed 11, spec 4, job 8, score 1, review 5); auto_labeling/operators
joins them, and the primitive package re-exports them by name, resolved
on first access so the shapes import does not cycle through the
operators. ``from sagemaker.ai_registry.data_preparer.auto_labeling
import prepare_round`` is the import path; where a function sits is
not part of it.

Every export carries one Example::. The API reference lists the 32
exports with autofunction and drops the 31 automodule blocks that
published all 337 names with :undoc-members:. The layout test asserts
the export lists, their examples, the lazy re-export, and that the
reference documents every export and only exports.

Step 5 of the per-primitive restructure (Pippin J9c9wKPhJ8QD0C).


* docs(data_preparer): State the operator contract as it is, with its exceptions

The contract said an operator writes no file and reads no project
directory by convention; three modules read the frozen split's state
by convention and two transfers write where the caller points. The
contract now names both: the downloads a caller asks for by path, and
the split guard's one convention (splits/split_state.json), which the
labeling round, the golden review and the split operators inherit. A
second primitive that needs a convention of its own adds it here.

Step 6 of the per-primitive restructure (Pippin J9c9wKPhJ8QD0C). The
other item under that step, prepare_round's 34 keyword arguments, is
tracked separately: no folder arrangement touches it.


* feat(data_preparer): Export the helpers a caller uses beside the operators

The agent skill that drives these operators reached into private modules
for the reads, lookups and refusals around them: reading a split file
with the client-read notice, the frozen split's state and test ids, the
run log's labeling runs, a review's logged decisions, the request
document and its size cap, the exceptions a caller catches. Each
subsystem now lists those beside its operators (operators, then
helpers, then exceptions and constants), and the client reads and the
row rule, which cut across the subsystems, are exported from the
operators package itself. 85 names: 68 functions, each with an
Example::, 11 exceptions, 6 constants. The primitive's lazy re-export
reads the list from operators.__all__, so one list governs both paths.

The API reference is regenerated from the export lists; the layout
test checks every function export has an example, every class export
is an exception, every constant is immutable, and the reference lists
exactly the function exports.


* fix(data_preparer): Review pass over the restructure

A bucket-root dataset location (a HubContentDocument with DatasetS3Bucket
and no prefix) resolved before the split; the one strict s3:// splitter
refused it. resolve_object lists the bucket for that case again, with a
test. DT_VIEW_SUFFIX was defined twice after the hub split; _scratch
takes dt_handoff's. Four of the new Example:: blocks named a signature
or a return shape wrongly (cold_start_sample_size's argument order,
is_unresolved's arity, review_rows' four-tuple, review_result's keys).


* refactor(data_preparer): Reuse the SDK's own hub name, file hash and S3 URI parser

Review found utilities the SDK already had. The derived AI Registry
hub name is AIRHub's derivation: it gains a pure hub_name_for(region,
account_id) (and hub_display_name_for) that its own initializer and the
labeling operators both call, so one place spells the hash. A file's
SHA-256 is sagemaker-core's hash_file. s3:// URI parsing is
sagemaker.core.s3.parse_s3_url / is_s3_url, with the operators' one
added rule that a key is required.

The byte transfers stay thin boto3 calls rather than S3Uploader /
S3Downloader: an operator is bound to a region by argument (a DataSet
ARN's own region) and those take a Session, which would add the
session's clients to every transfer; the module docstring says so.


* feat(data_preparer): The auto-labeling loop as seven project-level calls

A customer ran the operators as nineteen imports and as many steps. The
loop of the skill's full-loop.md is now one call per step, each
composing the step operators it already had and owning the project
folder the way the skill's templates did:

  inspect_data Step 0: inspect, detect the task, parse the label
                     set, gate the taxonomy; one report the rest takes
  prepare_seed Step 1: split the seed by label (the DT skill's
                     label strategy), freeze once, demos, folds; a cold
                     start draws the sample for people to label instead
  write_spec Step 1b: induce the rules from dev
  label_round Step 2: one job on a split, written as the
                     labeling_round template writes it
  refinement_rounds Steps 2-5 as an iterator: dev + val per spec
                     version, the scores and dev failures, and the
                     refine-or-stop routing of refinement-routing.md;
                     the person edits the spec between next() calls
  evaluate_specs Steps 5-6: scores.json from the jobs' held-out
                     reports, select (best-iter rollback, do-no-harm
                     floor), the shipped spec copied to labeling_spec.md
  label_corpus Step 7: the corpus run certified on the test split,
                     with the held-out review flag

Every job is the same prepare_round / submit_round / read_round call
with the arguments the skill passes (demos from dev, the split as its
own gold, scratch dataset names, test as the corpus run's gold); the
only judgment added is the Step 4 routing, taken from the skill's
reference. _run_log gains the on-disk writer in the skill's format.

Run on beta end to end: a 60-row seed and a 30-row corpus through a
refine round (val 0.933, refund->billing failures), a human edit, an
accept round (val 1.0), evaluate_specs shipping the refined spec, and
the corpus run registering the labeled DataSet with no labels on disk.


* refactor(data_preparer): refinement_rounds -> refine_spec

Review asked for verb-first names: the loop that labels dev and val per
spec version and reports what to refine is refine_spec.


* refactor(data_preparer): Prefix the project-level names with the primitive

Review: write_spec and the others are generic enough to collide with the
primitives that follow. inspect_labeling_data, prepare_labeling_seed,
draft_labeling_spec (a first spec from examples), run_labeling_round,
tune_labeling_spec (the rounds the person edits the spec between),
select_labeling_spec, label_corpus.

* feat(data_preparer): auto-labeling seed files, fold, Hub project calls and run report

* fix(data_preparer): Leave DatasetType out of the promoted DataSet version

The labeling job registers its output at document schema 5.0.0 with
DatasetType: SyntheticDataGeneration. promote_transform_output copied that
document for the next version, and ImportHubContent refuses a customer
document that carries it ("Unknown Dataset type provided"), so the
hand-off's overlay could not be promoted. DatasetType joins
ValidationManifest in the fields the service writes on its own
registrations and a new version leaves out.


* feat(data_preparer): seed.split_state writes the frozen split and its run-log entries


* feat(data_preparer): seed.bootstrap writes sample, merge and overlay

Move the non-HIL part of the auto-labeling skill's bootstrap_seed.py
(sample, merge, overlay) into operators/seed/bootstrap.py. The data
logic already in cold_start.py and labels.py is reused; this module
adds the checks main() made (target, task, row limit, prediction
field, the merge refusals), the file writes, and the review-set drop
and spot-check scoring. Exit 2 becomes DataPreparerOperatorError and
exit 1 (the seed does not name this corpus) becomes SeedMergeRefused.

Ports the skill's sample tests, adds merge/overlay/side-file tests,
and lists seed.bootstrap and seed.split_state in the layout test.


* feat(data_preparer): report primitive renders the run report

Move the auto-labeling skill's report.py into operators.report.render:
build_html and build_markdown render the end-of-loop report from the
same sections (the corpus run's job summary, fold spot-check, held-out
report and run log, or a local people-labeled labels.jsonl), and
write_report writes report.html and/or report.md after building both,
so a run that did not complete writes nothing. The split guard on a
gold file stays with the caller. Output matches the script byte for
byte on the ported fixtures.


* refactor(data_preparer): Export the split project layer under its own names

freeze_split, rehash_split, relabel_split, guard_split_read and log_test_read
write the files and the run-log entries; seed.split keeps the decisions under
the plain names. The export cap moves to 110 for the report and bootstrap
primitives.


* feat(data_preparer): The Hub doors and the adopted pick as a project uses them

job.hub_project: resolve_input writes the corpus.ref.json pointer, head.jsonl
and the provenance sidecar (or copies / downloads), record_scratch and
cleanup_scratch keep the scratch DataSet versions in the project's run log
and delete them at the hand-off, and the DT doors (dt_view_for_project,
promote_for_project, register_transform_output_for_project) record what they
register as scratch. spec.adopt gains adopt_job_pick and ship_adopted_spec,
which write decision.json and the adopted spec and re-check its bytes. These
are the write sides of the skill's hub_io.py and adopt_job_pick.py.


* fix(data_preparer): Name the templates in the operators' messages; guard a project with no split

The refusals and hand-off records named the skill's retired scripts
(hub_io.py, split_state.py, run_indexed_labeling); they now name the
code template and its action. guard_split_read on a project with no
frozen split returns None without touching a path.


* fix(data_preparer): Find a job's artifacts where its index sits; read a corpus pointer

LabelingSummary.from_dataset took the container's absolute Artifacts URIs,
which on beta now omit the synthetic-data-generation/<job>/<timestamp>/
level the service adds to the output folder, so every read-back failed
with NoSuchKey. The index's RelativePaths, resolved against the index's
own URI, find the files wherever the service put them; an artifact with
no relative path is kept as written.

read_first_row follows a corpus.ref.json pointer to its s3:// object, so
the inspect step takes the pointer a resolve wrote.


* fix(data_preparer): Find a review job's review/ folder in the SDG job folder

SDG output moved from <OutputS3Uri>/<JobName>-<createdAt>/ to
<OutputS3Uri>/synthetic-data-generation/<JobName>/<createdAt>/. review_folder
lists the job folder first, then the earlier prefix for a job that started
before the move; each prefix ends with the character that ends the folder
name, so a sibling job (job-10 for job-1) never matches. Ported from the
skill's fix on SDG_beta (CR-321077608).


* fix(data_preparer): Send Config.Review; refuse a Config key the typed options drop

labeling_options_from_document rebuilt the typed options from a request
document but never mapped Config.Review, so a label-review request was
submitted as an ordinary labeling job over the seed (billed, no review/
output). Review now maps to the typed Review, and a Config key the
function does not map is refused before anything is submitted, so a new
option cannot be dropped silently again. A round-trip test pins every
option the document carries.


* fix(auto-labeling): Poll review-only jobs instead of SDK wait

A review-only job (Config.Review) registers no DataSet, so the SDK's
generate(wait=True) raised "Completed job missing DatasetArn" on a job
that succeeded. Submit it with wait=False and poll DescribeJob to a
terminal state, the way a re-attach does. Labeling jobs keep the wait.


* feat(auto-labeling): Fold returned labels into the seed in the SDK

Add fold_human_labels, append_to_seed, check_fold and
spot_check_message to seed.bootstrap. They merge the rows people
reviewed with the labels they returned, score the spot-check against
the certificate or the 0.85 bar, append the rows to the seed
atomically, and prove an export was folded. Getting the labels from
people stays outside the SDK; these start from the returned export.
The four are exported from the auto_labeling import, so the operators
tree is unchanged.

* fix(auto-labeling): Make the taxonomy overlap check lexical-only

The gate's overlap check tried sentence-transformers first and fell
back to Jaccard token overlap, recording fallback_reason. The skill
never installs sentence-transformers, and an environment that has it
pulls a model from the network on first use. The check is now the
Jaccard overlap alone: overlap_pairs returns (pairs, method) with
method "lexical", and the report no longer carries fallback_reason.
This matches the skill-side change in CR-321402850.

* feat(data_preparer): fire-and-forget labeling rounds

submit_round and submit_labeling_job take wait=False: they return once
CreateJob succeeds, or once a re-attach finds the job still running,
with the job status read from DescribeJob. SubmittedRound.running says
whether the job has ended, and read_round refuses a running job. A
re-attach no longer re-uploads the spec, demos, gold and input; only a
new submission uploads them (before_submit).

prepare_round's note for a remote --eval no longer offers a download
when --eval is the --input object itself (one file with labeled and
unlabeled rows): that gold is the corpus.

run_context and check_run_id are exported from operators.job, so
callers stop importing job._run_context and job._round_parts.

* fix(data_preparer): resolve eleven high-severity security findings

* fix(data_preparer): resolve nine high-severity security findings

Resolves nine High findings from the first Continuous Security Evaluation
(the security scanner) scan of this release branch.

S3 bucket ownership (CWE-283/284): every S3 call in data_preparer built
its own boto3 client, so none of them asserted which account owns the
bucket. Names derived at runtime from dataset.source or MetadataS3Uri
could resolve to a squatted bucket whose contents are then parsed and
shown to the caller as their own job output. A new _s3_owner_kwargs
helper applies the pattern already settled in sagemaker-core
(session_helper.py:605-611, common_utils.py:436): ExpectedBucketOwner is
set only when the bucket is the session's own default bucket, so
legitimate cross-account dataset reads keep working.

Unbounded reads (CWE-400/770): _preview_output read an entire output
object in order to show 20 rows, and both line counters read whole
objects to count records, on customer corpora of arbitrary size. The
preview now issues a Range request and drops the truncated trailing
line. The counters stream in 1 MB chunks, carrying a partial line across
chunk boundaries, so the counts are unchanged and peak memory is
constant.

Job timeouts (CWE-1088): no public method exposed a timeout, so the
DataPreparerJobTimeoutError promised by their docstrings could never be
raised. generate, evaluate, transform, attach and stop now accept a
timeout and forward it to Job.wait(), which already supported one. The
default stays None, so no existing caller changes behaviour.

Cross-account hub ARNs (CWE-706/20): _parse_dataset_arn discarded the
partition, region and account of a hub-content ARN and returned a bare
hub name, which DescribeHubContent resolves in the caller's own account,
yielding the wrong dataset or nothing at all. It now returns a hub ARN
rebuilt from the ARN's own account and region.

A tenth finding, against the labeling summary read, was a false
positive: _read_s3_json delegates to Session.read_s3_file, which already
applies the ownership spot check.

Unit suite: 972 passed, 1 xfailed, against a baseline of 924 passed,
1 xfailed; 48 tests added. flake8 and black are clean. pylint scores
9.87 on this branch both before and after this change, with an identical
message set, so no lint debt is added. Note that 9.87 is already below
the fail-under 9.9 gate on this branch, independent of this change.


* fix(data_preparer): resolve cross-account hub ARNs in auto-labeling ops

Resolves two High findings from the the security scanner rescan after landed. Both
are the same defect already fixed in preparer.py on this branch, present
a second time in the operators package's own ARN handling.

register.parse_hub_content_arn returns a bare hub name and discards the
ARN's account segment, while deliberately keeping its region.
DescribeHubContent resolves a bare HubName in the caller's own account,
so a caller-supplied DataSet ARN naming another account's hub either
fails with ResourceNotFound or, worse, silently resolves a same-named
hub locally, whose DatasetS3Uri the pipeline then reads as its input.

Adds hub_arn_from_dataset_arn, which rebuilds the fully-qualified hub
ARN from the content ARN's own partition, region and account via
construct_hub_arn_from_name. HubName accepts either a name or an ARN, so
the two flagged lookups now resolve against the hub the ARN actually
names: resolve_dataset_ref (SEC-90E04A7E) and dt_view (SEC-07CCC6EC).

The return values of parse_dataset_arn and parse_hub_content_arn are
deliberately left unchanged. They are unpacked positionally at seven
sites, and three consumers require the bare hub name and would break on
an ARN:

  - register._normalize_source builds the short label f"{hub}/{name}"
  - dt_view passes HubName to import_hub_content, a write into a hub
    rather than a lookup, where ARN acceptance is unverified and an
    import into the wrong hub is worse than the finding
  - promote_transform_output compares hub names between two parsed ARNs

Each of those three has a regression test asserting it still receives a
bare hub name, so a future refactor fails loudly instead of silently
changing a write target.

Five further call sites share the same defect and are deliberately out
of scope here, belonging with the operators package's author:
register.py:169 and :233, dt_handoff.py:88-106, and dt_handoff.py:333.

Unit suite: 1616 passed, 1 xfailed, against 1605 passed, 1 xfailed
beforehand; 11 tests added. flake8 and black are clean.


* fix(data_preparer): address review feedback on the the security scanner security fixes

Four automated review comments on CR/PR , all marked Low. One was a
genuine regression introduced by the first commit.

_preview_output dropped everything after the final newline
unconditionally. That is only correct when the Range read truncated the
object; for a small complete file whose last record has no trailing
newline, it discarded that record, which the previous whole-object read
displayed. The tail is now dropped only when the read actually
truncated, so a complete body is decoded as-is. Three tests added,
including the multi-record no-trailing-newline case the original test
missed by covering only a single record.

The streaming line counters switched from splitlines() to
split(b"\n"), which differs on a bare \r. No behaviour change here, but
the comments now state which endings are covered (\n, and \r\n via
strip()) and that a bare-\r-delimited file is out of scope, instead of
claiming the semantics are preserved exactly. _output_has_no_records
deliberately keeps splitlines(): its body is bounded at 64 KB and
changing its splitting could alter the empty-check result.

Both hub-ARN builders now construct the ARN from the parsed partition
rather than calling construct_hub_arn_from_name, which derives the
partition from the region via aws_partition() and so may not round-trip
a cross-partition ARN. Output is identical for standard partitions; a
test covers an aws-cn ARN.

hub_arn_from_dataset_arn no longer carries its own copy of the
versionless trailing-slash heuristic. Normalize-and-parse is one private
helper that it and parse_hub_content_arn share. The parsers' return
values are unchanged, so the three consumers that require a bare hub
name, and their regression tests, are untouched.

Unit suite: 1620 passed, 1 xfailed, against 1616 passed, 1 xfailed
beforehand; 4 tests added, no existing test modified. flake8 clean under
the repo config (which ignores E203, as black requires) and black clean.


* fix(data_preparer): preview truncation boundary and hub-ARN scoping

Two remaining review comments on CR/PR , both Low.

_preview_output inferred truncation from the length of the Range read,
treating anything that filled the window as truncated. An object of
exactly _PREVIEW_MAX_BYTES whose last record has no trailing newline is
complete, but was classified as truncated and lost that record to the
tail-drop, which is the case the whole-object branch exists to protect.
Truncation now comes from the object's real size, read from the
response's ContentRange, so it is a fact rather than an inference. If
ContentRange is absent or unparseable the old heuristic still applies,
so behaviour is never worse than before.

Commit 2 switched only the resolve_dataset_ref and dt_view lookups to a
qualified hub ARN. The other describe_hub_content calls that take a
caller-supplied source ARN still pass a bare HubName and so still
resolve in the caller's own account. That omission is now documented
where someone would look for it: on parse_dataset_arn, which is the
function handing back the bare name, plus a comment at each of
promote_transform_output and register_transform_output.

The note is deliberately scoped to the source-side lookups. Call sites
that name the view this code is about to create, and every
import_hub_content write, correctly keep the bare name because the
target is the local hub; marking those as deficient would invite a
change that imports into the wrong hub.

The note names functions rather than line numbers. Earlier write-ups of
this change cited register.py:169 and :233, which were function
definition lines when first recorded and are now blank lines two commits
later. register.py's remaining bare-hub lookups are in
existing_datasets, delete_hub_content_version and _append_guard.

Unit suite: 1798 passed, 1 xfailed, against 1795 passed, 1 xfailed
beforehand; 3 tests added covering the exact-cap, genuinely-truncated
and missing-ContentRange paths. No existing test modified. flake8 clean
under the repo config and black clean.


* fix(data_preparer): sanitise induction prompts and re-verify Hub append

Two the security scanner findings in the auto-labeling operators.

Untrusted dataset row text was interpolated into the spec-induction
prompts, and the model's returned spec was written to disk and
re-uploaded as DatasetSpecification.SpecS3Uri, in both directions
unfiltered. Every text path folded newlines and did nothing else, so
carriage returns, other C0/C1 controls, zero-width characters, bidi
overrides and Unicode Tags characters passed through and could
restructure a prompt or the induced spec while staying invisible. A
single _scrub() now runs on all four row-to-prompt paths (_row_text,
both _anchor_text branches, _span_context and the NER span) and on
both model-output sites.

The character class is deliberately narrow. ZWNJ (U+200C), ZWJ
(U+200D) and U+2060-U+2065 are preserved: they are orthographically
required in Persian, Arabic and Devanagari and structural in emoji ZWJ
sequences, so stripping them corrupts legitimate text without
preventing any structural attack. The Tags block (U+E0000-U+E007F) is
stripped because those characters mirror printable ASCII invisibly and
are the standard ASCII-smuggling vector; the accepted cost is that
subdivision-flag emoji degrade to a plain U+1F3F4.

This closes the smuggling half of the prompt-injection findings. The
structural half, giving the prompts an explicit data/instruction
boundary, is left alone: it changes prompt text, which is governed by
the A/B gate on a held-out gold set.

register_labeled_output evaluated its Hub append guard before the S3
uploads and consumed the verdict after them, so a concurrent writer
could append a version in that window and the append that happened was
not the one the caller consented to. The guard is now re-run
immediately before import_hub_content; if the version or verdict moved,
registration is skipped with hub_error rather than appending an
unverified version, which is the cont…

This branch was previously deployed

1 inactive deployment
auto-approve — 43013693 Deployed Oct 27, 2026 by rsareddy0329 via wait-for-approval #763
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants