~~~python
# Bring-your-own-spec job — skill-caller lane (bring-your-own-spec.md Step 4S)
# Submits ONE dataset quality evaluation job against a spec the caller already has and prints the
# job name and ARN. With WAIT = True it then waits and prints the S3 URI of the job's
# metadata.json; with WAIT = False it ends after the submission, and the caller re-attaches
# later. Nothing else: no built-in metrics, no exploratory analysis, no report generation
# (the caller's page does that from metadata.json).
#
# Prerequisites: the SDK is installed as sagemaker-python-sdk-setup.md says, and the dataset is
# registered in the SageMaker AI Registry (DatasetArn).
# Every bracketed placeholder is filled by the agent from bring-your-own-spec.md Step 3; its
# placeholder table has a row for each placeholder (expected format and an example).
# Dependencies: sagemaker-core, sagemaker-train, boto3, and directory-management's scripts/run_log.py (the
# project's run-log writer), imported from RUN_LOG_WRITER_DIR.

# Cell 0 [markdown]: Bring-your-own-spec evaluation
# ⚠️ This evaluation uses Amazon Bedrock. [Bedrock Service Terms](https://aws.amazon.com/service-terms/) and pricing apply.
# A judge model chosen by the service scores the rows whenever the spec has criteria a model must judge, in the
# account running the job. The spec is the whole evaluation: no built-in metrics run.

# Cell 1: Configuration and imports

import json
import sys

import boto3
from sagemaker.core import Attribution, set_attribution
from sagemaker.core.helper.session_helper import Session
from sagemaker.core.resources import Job  # the lookup of a job by its name (Cell 3, a taken name)
from sagemaker.core.shapes import Tag  # the tag type evaluate() takes (Cell 3); the SDK sends it as Key/Value
from sagemaker.ai_registry import DataPreparer, DatasetJobConfig

set_attribution(Attribution.SAGEMAKER_AGENT_PLUGIN)

DATASET_ARN = "[DATASET_ARN]"            # Hub content ARN of the registered dataset
OUTPUT_S3_URI = "[OUTPUT_S3_URI]"        # S3 prefix the job writes its output folder under
JOB_NAME = "[JOB_NAME]"                  # the job's exact name: ASCII letters, digits and hyphens, at most 63 characters; one per copy of this template
ROLE_ARN = [ROLE_ARN]                    # the role bring-your-own-spec.md Step 3 settled, "<role arn>" (quoted; the caller's role when it passed one); None (unquoted) only when the session identity is itself a SageMaker execution role
SPEC_S3_URI = [SPEC_S3_URI]              # "s3://.../specs/<file>.md" (quoted), or None when CODE_ARTIFACT_S3_URI is set
CODE_ARTIFACT_S3_URI = [CODE_ARTIFACT_S3_URI]  # an earlier job's spec_eval/ folder (its Reports.SpecEval judge_code.py URI without the file name), else None
PII_VIEWS = [PII_VIEWS]                  # None, or [{"Role": "Text", "Column": "<column>"}, ...] each column once, or [{"Role": "Messages", "Column": "<column>"}]: one pii_detection operation, only when a calling capability names them
METRIC_VIEWS = [METRIC_VIEWS]            # None, or [{"Operator": "exact_dedup" or "fuzzy_dedup" or "language_detection", "Column": "<flat text column>", "Params": {...}}, ...], each operator and column once, beside a spec or code artifact, only when a calling capability names them
DOWN_SAMPLE_RECORD_COUNT = [DOWN_SAMPLE_RECORD_COUNT]  # None, or an integer only when the caller asked for a sample
JUDGE_MODEL_ID = [JUDGE_MODEL_ID]        # None (unquoted) unless the caller named a model, then "<model id>" (quoted); the service applies its default
CONTEXT_DOCUMENTS_S3_URI = [CONTEXT_DOCUMENTS_S3_URI]  # None (unquoted) unless the caller brought reference documents for context: documents criteria, then "s3://.../reference-docs/" (quoted; a folder URI ending in "/")
WAIT = [WAIT]                            # True: the caller reads metadata.json next, so wait for the job. False: start it, print its name and ARN, and end
ATTACH_JOB_ARN = [ATTACH_JOB_ARN]        # None, or the ARN this copy printed when it launched the job with WAIT = False: attach to it and collect its result, no submission (needs WAIT = True)
PROJECT_ID = [PROJECT_ID]                # "<ProjectId>" (quoted) when a SageMaker Project is active in the conversation, else None (unquoted): the job then carries no tag
PROJECT_DIR = "[PROJECT_DIR]"            # the project directory whose run-log.jsonl records this job, relative or absolute
RUN_LOG_STEP = "[RUN_LOG_STEP]"          # the plan step's name in kebab-case; outside a plan, the task's name
RUN_LOG_ITERATION = [RUN_LOG_ITERATION]  # the iteration integer; 0 for setup and the baseline
RUN_LOG_FIELDS = [RUN_LOG_FIELDS]        # {} (unquoted), or a dict of extra fields the caller names for the launch entry
RUN_LOG_WRITER_DIR = "[RUN_LOG_WRITER_DIR]"  # the absolute path of directory-management's scripts/ directory in the installed skill

if RUN_LOG_WRITER_DIR not in sys.path:
    sys.path.insert(0, RUN_LOG_WRITER_DIR)
import run_log  # the project's run-log writer (directory-management)

def _has_code(error, wanted):
    """True when the service refused the submission with the error code `wanted`."""
    for _ in range(10):  # the error, then the errors it was raised from
        if error is None:
            return False
        response = getattr(error, "response", None)
        code = (response.get("Error") or {}).get("Code") if isinstance(response, dict) else None
        if code == wanted or (code is None and wanted in str(error)):
            return True
        error = error.__cause__ or error.__context__
    return False


def _name_taken(error):
    """True when the submission was refused because a job already holds the name (the service's ResourceInUse)."""
    return _has_code(error, "ResourceInUse")


def _limit_exceeded(error):
    """True when the account's limit of jobs at once refused the submission (ResourceLimitExceeded)."""
    return _has_code(error, "ResourceLimitExceeded")

# Cell 2: Assemble the job configuration

if (not JOB_NAME.isascii() or JOB_NAME.startswith("-") or not JOB_NAME.replace("-", "").isalnum()
        or len(JOB_NAME) > 63):
    raise ValueError(f"JOB_NAME must start with a letter or digit, use only ASCII letters, digits and hyphens, "
                     f"and have at most 63 characters; got {JOB_NAME!r}")
if SPEC_S3_URI and CODE_ARTIFACT_S3_URI:
    raise ValueError("set at most one of SPEC_S3_URI and CODE_ARTIFACT_S3_URI")
if not (SPEC_S3_URI or CODE_ARTIFACT_S3_URI or PII_VIEWS):
    raise ValueError("set SPEC_S3_URI, CODE_ARTIFACT_S3_URI or PII_VIEWS")
# DOWN_SAMPLE_RECORD_COUNT, JUDGE_MODEL_ID and CONTEXT_DOCUMENTS_S3_URI configure spec_eval; with PII views alone there is none.
for _name, _value in (("DOWN_SAMPLE_RECORD_COUNT", DOWN_SAMPLE_RECORD_COUNT), ("JUDGE_MODEL_ID", JUDGE_MODEL_ID),
                      ("CONTEXT_DOCUMENTS_S3_URI", CONTEXT_DOCUMENTS_S3_URI)):
    if _value is not None and not (SPEC_S3_URI or CODE_ARTIFACT_S3_URI):
        raise ValueError(f"{_name} configures spec_eval, so it needs SPEC_S3_URI or CODE_ARTIFACT_S3_URI")
# The views a calling capability names beside the spec (bring-your-own-spec.md Step 3): a PII scan per column, and
# the model-free metrics each bound to one flat text column (Params never holds a View). Checked before any session.
VIEW_METRICS = ("exact_dedup", "fuzzy_dedup", "language_detection")
if PII_VIEWS is not None and (
        not isinstance(PII_VIEWS, list) or not PII_VIEWS
        or not all(isinstance(v, dict) and set(v) == {"Column", "Role"} and v["Role"] in ("Text", "Messages")
                   and isinstance(v["Column"], str) and v["Column"] for v in PII_VIEWS)
        or len({v["Column"] for v in PII_VIEWS}) != len(PII_VIEWS)
        or (any(v["Role"] == "Messages" for v in PII_VIEWS) and len(PII_VIEWS) != 1)):
    raise ValueError('PII_VIEWS is None or a list of {"Role": "Text", "Column"} views, each column once, or of one '
                     '{"Role": "Messages", "Column"}: they run as one pii_detection operation')
if METRIC_VIEWS is not None and (
        not isinstance(METRIC_VIEWS, list) or not METRIC_VIEWS
        or not all(isinstance(v, dict) and {"Operator", "Column"} <= set(v) <= {"Operator", "Column", "Params"}
                   and v["Operator"] in VIEW_METRICS and isinstance(v["Column"], str) and v["Column"]
                   and isinstance(v.get("Params", {}), dict) and "View" not in v.get("Params", {})
                   for v in METRIC_VIEWS)
        or len({(v["Operator"], v["Column"]) for v in METRIC_VIEWS}) != len(METRIC_VIEWS)):
    raise ValueError('METRIC_VIEWS is None or a list of {"Operator": ' + " or ".join(VIEW_METRICS)
                     + ', "Column", "Params" (optional, no View)}, each operator and column once')
if METRIC_VIEWS and not (SPEC_S3_URI or CODE_ARTIFACT_S3_URI):
    raise ValueError("METRIC_VIEWS run beside SPEC_S3_URI or CODE_ARTIFACT_S3_URI, never alone")
if ATTACH_JOB_ARN is not None and not WAIT:
    raise ValueError("ATTACH_JOB_ARN collects a launched job's result: set WAIT = True")
# The launch entry's own fields and the writer's reserved keys; RUN_LOG_FIELDS may name none of them.
LAUNCH_FIELDS = ("job_name", "dataset_arn", "output_s3_uri") + tuple(run_log.RESERVED)
if not isinstance(RUN_LOG_FIELDS, dict) or set(RUN_LOG_FIELDS) & set(LAUNCH_FIELDS):
    raise ValueError("RUN_LOG_FIELDS is a dict without the keys " + ", ".join(LAUNCH_FIELDS))

spec_eval_config = {"SpecS3Uri": SPEC_S3_URI} if SPEC_S3_URI else {"CodeArtifactS3Uri": CODE_ARTIFACT_S3_URI}
if DOWN_SAMPLE_RECORD_COUNT:
    spec_eval_config["DownSampleRecordCount"] = int(DOWN_SAMPLE_RECORD_COUNT)
if JUDGE_MODEL_ID:
    spec_eval_config["ModelConfig"] = {"JudgeModelConfig": {"ModelId": JUDGE_MODEL_ID}}
if CONTEXT_DOCUMENTS_S3_URI:
    if not CONTEXT_DOCUMENTS_S3_URI.endswith("/"):
        raise ValueError("CONTEXT_DOCUMENTS_S3_URI must be an S3 folder URI ending in /")
    spec_eval_config["ContextDocumentsS3Uri"] = CONTEXT_DOCUMENTS_S3_URI

dq_config = DatasetJobConfig(
    input_data_config=[{"DatasetArn": DATASET_ARN}],
    output_data_config={"S3OutputPath": OUTPUT_S3_URI},
    schema_version="3.0.0",              # required pin; unpinned resolves an older request version
)
# spec_eval when a spec or code artifact is set, plus one operation per view the caller named (dataset-service-api.md: entries compose freely); never default_metrics
operations = [{"Operator": "spec_eval", "Config": spec_eval_config}] if (SPEC_S3_URI or CODE_ARTIFACT_S3_URI) else []
operations += [{"Operator": v["Operator"], "Config": {"View": [{"Role": "Text", "Column": v["Column"]}], **v.get("Params", {})}}
               for v in METRIC_VIEWS or []]
operations += [{"Operator": "pii_detection", "Config": {"View": PII_VIEWS}}] if PII_VIEWS else []
dq_config.evaluation_config = {"Operations": operations}

# Cell 3: Submit; then wait and read the metadata URI, or hand back the job

REGION = DATASET_ARN.split(":")[3]            # the dataset's region is the job's region; nothing else decides it
session = Session(boto_session=boto3.Session(region_name=REGION))
preparer = DataPreparer(sagemaker_session=session, **({"role": ROLE_ARN} if ROLE_ARN else {}))  # the name goes on evaluate()

if ATTACH_JOB_ARN:
    # This copy launched and recorded the job earlier (WAIT = False): attach to it and wait below; no submission.
    job_name, job = ATTACH_JOB_ARN.rsplit("/", 1)[-1], DataPreparer.attach(ATTACH_JOB_ARN, wait=False, sagemaker_session=session)
else:
    job_name = JOB_NAME
    try:
        # job_name= sets the exact service name (dataset-service-api.md); a full quota or a throttle raises the
        # service's error here, with no job started.
        job = preparer.evaluate(dq_config, wait=False, job_name=JOB_NAME,
                                **({"tags": [Tag(key="sagemaker:project-id", value=PROJECT_ID)]} if PROJECT_ID else {}))  # submits; returns the Job handle
        run_log.record_job(PROJECT_DIR, step=RUN_LOG_STEP, iteration=RUN_LOG_ITERATION, status="launched", arn=job.job_arn,
                           job_name=job_name, dataset_arn=DATASET_ARN, output_s3_uri=OUTPUT_S3_URI, **RUN_LOG_FIELDS)
    except Exception as error:  # the job limit (ResourceLimitExceeded) or a taken name (ResourceInUse)
        if _limit_exceeded(error):
            # The account's limit of DQ jobs at once is reached: this call started no job and recorded
            # nothing. Step 4S of references/bring-your-own-spec.md hands it back; the caller relaunches.
            print(json.dumps({"limit_exceeded": True, "job_name": JOB_NAME, "message": str(error)}))
            raise
        if not _name_taken(error):
            raise
        # A job of this name reached the service before. Attach only when it is this submission's job (the same
        # dataset and output prefix); record its launch only when the run log has none; never submit it again.
        taken = Job.get(job_name=JOB_NAME, job_category="DataQualityEvaluation", session=session.boto_session)

        def _values(node, key):
            # Every value of `key` anywhere in the job's config document.
            if isinstance(node, dict):
                return [v for k, v in node.items() if k == key] + [x for v in node.values() for x in _values(v, key)]
            return [x for v in node for x in _values(v, key)] if isinstance(node, list) else []

        document = json.loads(taken.job_config_document or "{}")
        inputs, outputs = _values(document, "DatasetArn"), _values(document, "S3OutputPath")
        prefix = OUTPUT_S3_URI.rstrip("/")
        if DATASET_ARN not in inputs or not any(
                isinstance(o, str) and (o.rstrip("/") == prefix or o.startswith(prefix + "/")) for o in outputs):
            raise SystemExit(f"a job named {JOB_NAME} exists ({taken.job_arn}) but is not this submission's: its input "
                             f"{inputs or 'unknown'} and output {outputs or 'unknown'} are not {DATASET_ARN} and "
                             f"{OUTPUT_S3_URI}; give this job another [JOB_NAME], or set [ATTACH_JOB_ARN] to collect that "
                             "job on purpose")
        job = DataPreparer.attach(taken.job_arn, wait=False, sagemaker_session=session)
        if not run_log.read_entries(PROJECT_DIR, kind="job", arn=taken.job_arn):
            run_log.record_job(PROJECT_DIR, step=RUN_LOG_STEP, iteration=RUN_LOG_ITERATION, status="launched",
                               arn=taken.job_arn, job_name=job_name, dataset_arn=DATASET_ARN, output_s3_uri=OUTPUT_S3_URI,
                               **RUN_LOG_FIELDS)
print(json.dumps({"job_name": job_name, "job_arn": job.job_arn}))

if WAIT:
    # The caller needs MetadataS3Uri, which DescribeJob returns only at completion.
    job.wait()                                  # polls until terminal; does NOT raise on failure

    # The handle carries the DescribeJob fields after the wait.
    # The result entry goes to the run log on every end state, before the exit.
    if job.job_status != "Completed":
        run_log.record_job(PROJECT_DIR, step=RUN_LOG_STEP, iteration=RUN_LOG_ITERATION,
                           status="stopped" if job.job_status == "Stopped" else "failed", arn=job.job_arn,
                           job_name=job_name, dataset_arn=DATASET_ARN, failure_reason=job.failure_reason)
        raise SystemExit(f"{job.job_name} ended {job.job_status}: {job.failure_reason or 'no failure reason given'}")
    metadata_s3_uri = json.loads(job.job_config_document).get("MetadataS3Uri")  # job_config_document is a JSON string
    run_log.record_job(PROJECT_DIR, step=RUN_LOG_STEP, iteration=RUN_LOG_ITERATION, status="completed", arn=job.job_arn,
                       job_name=job_name, dataset_arn=DATASET_ARN, metadata_s3_uri=metadata_s3_uri)
    if not metadata_s3_uri:  # no MetadataS3Uri (troubleshooting.md)
        raise SystemExit(f"{job.job_name} completed without MetadataS3Uri; find its outputs with "
                         f"dataset-quality/scripts/dq_job_output.py --job-arn {job.job_arn}")
    print(json.dumps({"job_name": job_name, "job_arn": job.job_arn, "job_status": job.job_status,
                      "metadata_s3_uri": metadata_s3_uri}))
else:
    # The caller collects the result later by running this copy again with ATTACH_JOB_ARN set to the ARN above and
    # WAIT = True: it attaches, waits and writes the result entry (bring-your-own-spec.md Step 4S item 3).
    print(f"Submitted; not waiting. Re-attach later with job_arn: {job.job_arn}")
~~~