Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Bulk test-case creation skips existing fully qualified names

- **Status:** Accepted
- **Revisions:** v1 2026-10-21 (initial), v2 2026-10-21 (shared bulk-create recovery), v3 2026-10-21 (preparation races), v4 2026-10-21 (per-input outcomes and conflict policy), v5 2026-10-21 (SDK defaults and retry behavior)
- **Deciders:** Harsha
- **Guard:** `TestCaseResourceIT`, `GlossaryTermResourceIT`, `EntityBulkCreateRecoveryIT`, `BulkCreateFluentAPITest`, `ingestion/tests/unit/sdk/test_bulk_create.py`
- **Related:** `POST /api/v1/dataQuality/testCases/createMany`

## Context

Automated test creation can submit an already existing test alongside new tests. A duplicate FQN
previously rejected the entire batch, preventing the new tests from being created.

## Decision

The bulk test-case endpoint skips existing FQNs, including soft-deleted tests, without updating or
restoring them. Repeated FQNs within a request use the first occurrence. The response contains only
newly created tests, in request order, and is empty when every test is skipped.

The existing request size limit of 100 keeps the inserts in one transaction. If a concurrent request
wins an insert, the failed transaction rolls back before a fresh lookup removes the winner and
retries the remaining tests. Each retry must remove at least one conflicting FQN, bounding retries
by the request size. Other errors, or duplicate-key errors without a matching existing FQN, propagate.

## Consequences

Callers can safely repeat bulk creation without overwriting existing tests. They must use the
returned FQNs rather than assume one result per submitted item. Skipped tests receive no new
relationships or creation events. Single-test creation and other entities keep their existing behavior.

## Amendment v2: shared bulk-create recovery

`EntityRepository.createMany` now owns this behavior for every caller, including glossary terms.
Entity-specific validation still runs for all new entries before any writes. FQN lookup precedes
validation because some repositories reject existing names during preparation rather than at INSERT.
Glossary rules for conflicting names under different parents remain validation errors.

Recovery is limited to the failed transaction's chunk of at most 100 entities. Each successful chunk
finishes its creation hooks before the next chunk starts, so a later failure neither replays committed
rows nor leaves them without search indexing and creation events. Concurrent duplicates are skipped
after rollback with a warning, and only the remaining new entries in that chunk are retried. Recovery
requires a matching FQN with a different stored ID; an unrelated unique constraint or a failure after
our own rows committed still propagates. Previously committed chunks remain committed on other errors.

This supersedes the v1 limitation to test cases. Single-entity creation and bulk create-or-update
retain their existing contracts; updates are not converted into skips. API responses still contain
only newly created entities, so clients must not assume one result per submitted item.

## Amendment v3: concurrent creation during preparation

A concurrent request can create an FQN after the initial lookup but before validation. When
preparation rejects an entry, recovery rechecks that exact FQN and skips it only if another ID now
exists. Otherwise, the original validation error propagates before any batch writes. This preserves
glossary name validation for different parents, whose FQNs differ even when their names match.

## Amendment v4: explicit outcomes and request conflict policy

Both test-case and glossary-term `createMany` endpoints return a `BulkCreateResult` when the
request explicitly supplies `onConflict=skip` or `onConflict=fail`. Omitting the parameter preserves
the created-entity array and rejects validation errors before writes, as existing clients expect. The response contains `createdCount`, `skippedCount`, `failedCount`, and one result per
input in request order. Each result includes its zero-based input index, FQN when it can be resolved,
and `created`, `skipped`, or `failed` status. Skipped and failed results include a stable reason code
and a readable message. An ID is returned only for a newly created entity. Conflict results do not expose stored IDs
because permission to create does not imply permission to read the existing entity.

The `onConflict` query parameter accepts `skip` or `fail`. Legacy requests skip conflicts. It applies to existing FQNs,
including soft-deleted entities, repeated FQNs in the request, and concurrent winners during
preparation or insertion. `fail` marks the conflicting input as failed and continues with other
valid inputs; it does not mean all-or-nothing request execution. Both policies preserve existing
entities. Repeated new names use the first valid occurrence. An input that fails mapping or preparation
does not reserve its FQN; a later valid occurrence can be created.

With an explicit policy, entity mapping and preparation validation failures are reported per input as `VALIDATION_ERROR`;
valid inputs continue. Conflicts use `ALREADY_EXISTS` or `DUPLICATE_IN_REQUEST`. Authentication,
authorization, malformed requests, request limits, and unexpected storage or post-commit failures
remain HTTP errors. Those errors may occur after earlier transaction chunks committed, as in v2;
the API does not promise request-wide atomicity or reinterpret infrastructure errors as skips.

The Java SDK keeps its existing `createMany(requests)` list return type and adds an explicit-policy
overload returning the detailed result. This preserves Collate AI's existing array parser without a
coordinated rollout. Consumers opting in must inspect the ordered outcomes and failure reasons.
Generated Java, Python, and TypeScript models share the response schema. The bulk create-or-update
API keeps its separate contract.

## Amendment v5: SDK defaults and retry behavior

The Java fluent and Python SDK bulk-create facades default to `onConflict=skip`, always request
the detailed `BulkCreateResult`, and are unsupported against servers without `onConflict`.
This applies to both `TestCases` and `GlossaryTerms`; the legacy Java service overload in v4
keeps its existing array response.

The Python facades disable REST-level retries for the bulk POST (`retries=0`). A 503 or 504 can
arrive after chunks committed, and replaying the batch would replace the original created outcomes
with conflicts. HTTP errors propagate; an empty or missing response raises a clear `RuntimeError`
instead of a model validation error. Neither error proves that creation rolled back.
25 changes: 25 additions & 0 deletions ingestion/src/metadata/sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,31 @@ Tables.delete(str(updated.id.root), recursive=True, hard_delete=True)
entity by `entity.id` and patches the changed fields through the underlying
OpenMetadata client.

## Bulk Creation with Conflict Outcomes

`TestCases.create_many()` and `GlossaryTerms.create_many()` return a typed
`BulkCreateResult`. Pass generated create requests as a list:

```python
from metadata.generated.schema.api.data.createGlossaryTerm import CreateGlossaryTermRequest
from metadata.generated.schema.type.bulkCreateResult import ConflictPolicy
from metadata.sdk import GlossaryTerms

result = GlossaryTerms.create_many(
[CreateGlossaryTermRequest(name="Revenue", glossary="Finance", description="Recognized revenue")],
on_conflict=ConflictPolicy.skip,
)
print(result.createdCount, result.skippedCount, result.failedCount)
for item in result.results:
print(item.index, item.status.value, item.reason, item.message)
```

The default policy is `skip`. `ConflictPolicy.fail` marks conflicts as failed
while valid inputs continue. Both methods explicitly request detailed outcomes;
each input has an index, status, and a reason/message when skipped or failed.
Created inputs also have an ID. Request-level errors still raise `APIError`.
These methods require a server that supports the `onConflict` parameter.

## Listing and Pagination

`list()` returns one page as an `EntityList` with `entities`, `after`, and
Expand Down
18 changes: 18 additions & 0 deletions ingestion/src/metadata/sdk/entities/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import builtins # noqa: TC003
import json
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass, field
from typing import (
Expand All @@ -14,6 +15,7 @@
)

from metadata.generated.schema.type.basic import FullyQualifiedEntityName # noqa: TC001
from metadata.generated.schema.type.bulkCreateResult import BulkCreateResult, ConflictPolicy
from metadata.ingestion.models.custom_pydantic import BaseModel
from metadata.sdk.client import OpenMetadata
from metadata.sdk.types import JsonDict, OMetaClient, UuidLike
Expand Down Expand Up @@ -188,6 +190,22 @@ def create(cls, request: TCreate) -> TEntity:
response = client.create_or_update(request)
return cls._coerce_entity(response)

@classmethod
def _create_many(cls, requests: Sequence[TCreate], on_conflict: ConflictPolicy) -> BulkCreateResult:
client = cls._get_client()
endpoint = cls._get_endpoint_path(client)
# REST drops empty json lists; data preserves an empty batch as [].
payload = json.dumps(
[request.model_dump(mode="json", by_alias=True, exclude_none=True) for request in requests]
)
# A gateway error may follow a commit; replaying would lose the original created outcomes.
response = cls._get_rest_client(client).post(
f"{endpoint}/createMany?onConflict={on_conflict.value}", data=payload, retries=0
)
if response is None:
raise RuntimeError(f"No response from {endpoint}/createMany; creation may have completed")
return BulkCreateResult.model_validate(response)
Comment on lines +193 to +207

@gitar-bot gitar-bot Bot Oct 21, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Bug: Python create_many retries non-idempotent POST on 503/504

_create_many calls rest_client.post(...) with the client's default retry budget (retry=3, retry_codes=[503, 504], see ingestion/src/metadata/ingestion/ometa/client.py:186-189,386). Suppose a proxy returns 504 after the server has already committed some chunks. The SDK then sends the same batch again, and the retry reports every entity the first attempt created as skipped/ALREADY_EXISTS (or failed under fail) with no IDs. The caller gets a result that says nothing was created. Separately, if the retries run out or the catch-all in _one_request swallows an error, _request returns None and BulkCreateResult.model_validate(None) raises a pydantic ValidationError instead of APIError. The fix is to pass retries=0 for this POST and to raise a clear error when the response is empty.

Disable automatic retries for the non-idempotent bulk POST and fail clearly on an empty response:

response = cls._get_rest_client(client).post(
    f"{endpoint}/createMany?onConflict={on_conflict.value}", data=payload, retries=0
)
if response is None:
    raise RuntimeError(f"No response from {endpoint}/createMany")
return BulkCreateResult.model_validate(response)

✅ Fixed by @harshach in c2824d2

Reply for a change | Was this helpful? React with 👍 / 👎

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in c2824d2. The shared Python bulk-create helper now sends the POST with retries=0. A missing response raises a clear RuntimeError naming the endpoint and noting that creation may have completed, rather than a Pydantic validation error. HTTP errors still propagate.

Added 14 regression cases through the real REST client for both facades: 503/504 are not replayed under either conflict policy, and empty/null responses or swallowed client errors fail clearly. All 14 failed before the fix and now pass. Full Python SDK suite: 486 passed, 1 existing skip.


@classmethod
def retrieve(
cls,
Expand Down
8 changes: 8 additions & 0 deletions ingestion/src/metadata/sdk/entities/glossaryterms.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
CreateGlossaryTermRequest,
)
from metadata.generated.schema.entity.data.glossaryTerm import GlossaryTerm
from metadata.generated.schema.type.bulkCreateResult import BulkCreateResult, ConflictPolicy
from metadata.sdk.entities.base import BaseEntity
from metadata.sdk.types import UuidLike

Expand All @@ -30,6 +31,13 @@ def entity_type(cls) -> type[GlossaryTerm]:
"""Return the GlossaryTerm entity type"""
return GlossaryTerm

@classmethod
def create_many(
cls, requests: Sequence[CreateGlossaryTermRequest], *, on_conflict: ConflictPolicy = ConflictPolicy.skip
) -> BulkCreateResult:
"""Create terms with per-input outcomes; fail marks conflicts failed while other inputs continue."""
return cls._create_many(requests, on_conflict)

# ------------------------------------------------------------------
# Typed relations
# ------------------------------------------------------------------
Expand Down
10 changes: 10 additions & 0 deletions ingestion/src/metadata/sdk/entities/testcases.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@
TestCases entity SDK with fluent API
"""

from collections.abc import Sequence

from metadata.generated.schema.api.tests.createTestCase import CreateTestCaseRequest
from metadata.generated.schema.tests.testCase import TestCase
from metadata.generated.schema.type.bulkCreateResult import BulkCreateResult, ConflictPolicy
from metadata.sdk.entities.base import BaseEntity


Expand All @@ -14,3 +17,10 @@ class TestCases(BaseEntity[TestCase, CreateTestCaseRequest]):
def entity_type(cls) -> type[TestCase]:
"""Return the TestCase entity type"""
return TestCase

@classmethod
def create_many(
cls, requests: Sequence[CreateTestCaseRequest], *, on_conflict: ConflictPolicy = ConflictPolicy.skip
) -> BulkCreateResult:
"""Create test cases with per-input outcomes; fail marks conflicts failed while other inputs continue."""
return cls._create_many(requests, on_conflict)
179 changes: 179 additions & 0 deletions ingestion/tests/unit/sdk/test_bulk_create.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
# Copyright 2026 Collate
# Licensed under the Collate Community License, Version 1.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://github.com/open-metadata/OpenMetadata/blob/main/ingestion/LICENSE
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Exercise fluent bulk creation through the real HTTP serialization boundary."""

import json
from unittest.mock import MagicMock
from uuid import UUID

import pytest
from requests import Response

from metadata.generated.schema.api.data.createGlossaryTerm import CreateGlossaryTermRequest
from metadata.generated.schema.api.tests.createTestCase import CreateTestCaseRequest
from metadata.generated.schema.entity.services.connections.metadata.openMetadataConnection import OpenMetadataConnection
from metadata.generated.schema.type.bulkCreateResult import BulkCreateResult, ConflictPolicy, Reason, Status
from metadata.ingestion.ometa.client import APIError
from metadata.ingestion.ometa.ometa_api import OpenMetadata
from metadata.sdk import GlossaryTerms, TestCases

CREATED_ID = "550e8400-e29b-41d4-a716-446655440000"


@pytest.fixture(params=["testCases", "glossaryTerms"])
def bulk_api(request, monkeypatch):
client = OpenMetadata(
OpenMetadataConnection(
hostPort="http://localhost:8585/api",
authProvider="openmetadata",
securityConfig={"jwtToken": "test-token"},
enableVersionValidation=False,
),
additional_client_config_arguments={"retry_wait": 0},
)
send = MagicMock()
monkeypatch.setattr(client.client._session, "send", send)
if request.param == "testCases":
facade = TestCases
payload = {
"name": "row_count",
"entityLink": "<#E::table::service.db.schema.table>",
"testDefinition": "tableRowCountToEqual",
}
create_request = CreateTestCaseRequest(**payload)
endpoint = "dataQuality/testCases"
else:
facade = GlossaryTerms
payload = {"name": "Revenue", "description": "Revenue in €", "glossary": "Finance"}
create_request = CreateGlossaryTermRequest(**payload)
endpoint = "glossaryTerms"
monkeypatch.setattr(facade, "_default_client", client)
yield facade, create_request, endpoint, payload, send
client.close()


def response(payload, status=200):
result = Response()
result.status_code = status
result.headers["Content-Type"] = "application/json"
result._content = json.dumps(payload).encode()
return result


def outcomes(policy):
conflict_status = "skipped" if policy is ConflictPolicy.skip else "failed"
return {
"onConflict": policy.value,
"createdCount": 1,
"skippedCount": 2 if policy is ConflictPolicy.skip else 0,
"failedCount": 1 if policy is ConflictPolicy.skip else 3,
"results": [
{"index": 0, "status": "created", "id": CREATED_ID, "fullyQualifiedName": "entity.created"},
{"index": 1, "status": conflict_status, "reason": "ALREADY_EXISTS", "message": "Entity already exists"},
{"index": 2, "status": conflict_status, "reason": "DUPLICATE_IN_REQUEST", "message": "Repeated input"},
{"index": 3, "status": "failed", "reason": "VALIDATION_ERROR", "message": "Invalid input"},
],
}


@pytest.mark.parametrize("policy", [None, ConflictPolicy.skip, ConflictPolicy.fail])
def test_bulk_create_sends_policy_and_parses_outcomes(bulk_api, policy):
facade, create_request, endpoint, payload, send = bulk_api
expected_policy = policy or ConflictPolicy.skip
send.return_value = response(outcomes(expected_policy))

options = {} if policy is None else {"on_conflict": policy}
result = facade.create_many([create_request] * 4, **options)

assert send.call_count == 1

Check warning on line 96 in ingestion/tests/unit/sdk/test_bulk_create.py

View check run for this annotation

SonarQubeCloud / [open-metadata-ingestion] SonarCloud Code Analysis

Unify assertion argument order in this file; both "actual first" and "expected first" conventions are used.

See more on https://sonarcloud.io/project/issues?id=open-metadata-ingestion&issues=AaFgDNhC1XP70KwUjY7P&open=AaFgDNhC1XP70KwUjY7P&pullRequest=35910
sent = send.call_args.args[0]
assert sent.method == "POST"
assert sent.url == f"http://localhost:8585/api/v1/{endpoint}/createMany?onConflict={expected_policy.value}"
body = json.loads(sent.body)
assert len(body) == 4
for item in body:
assert payload.items() <= item.items()
assert isinstance(result, BulkCreateResult)
assert result.onConflict is expected_policy
assert (result.createdCount, result.skippedCount, result.failedCount) == (
(1, 2, 1) if expected_policy is ConflictPolicy.skip else (1, 0, 3)
)
assert [item.index for item in result.results] == [0, 1, 2, 3]
assert result.results[0].id.root == UUID(CREATED_ID)
assert result.results[0].status is Status.created
assert result.results[0].fullyQualifiedName.root == "entity.created"
conflict_status = Status.skipped if expected_policy is ConflictPolicy.skip else Status.failed
assert [item.status for item in result.results[1:]] == [conflict_status, conflict_status, Status.failed]
assert [item.reason for item in result.results[1:]] == [
Reason.ALREADY_EXISTS,
Reason.DUPLICATE_IN_REQUEST,
Reason.VALIDATION_ERROR,
]
assert [item.message for item in result.results[1:]] == ["Entity already exists", "Repeated input", "Invalid input"]
assert all(item.id is None for item in result.results[1:])


def test_empty_batch_is_sent_as_json_array(bulk_api):
facade, _, _, _, send = bulk_api
send.return_value = response(
{"onConflict": "skip", "createdCount": 0, "skippedCount": 0, "failedCount": 0, "results": []}
)

result = facade.create_many([])

assert send.call_args.args[0].body == "[]"
assert result.results == []
assert (result.createdCount, result.skippedCount, result.failedCount) == (0, 0, 0)


def test_http_errors_are_not_reported_as_item_outcomes(bulk_api):
facade, create_request, _, _, send = bulk_api
send.return_value = response({"code": 403, "message": "Permission denied"}, status=403)

with pytest.raises(APIError, match="Permission denied"):
facade.create_many([create_request])


@pytest.mark.parametrize("status", [503, 504])
@pytest.mark.parametrize("policy", [ConflictPolicy.skip, ConflictPolicy.fail])
def test_bulk_create_does_not_retry_gateway_errors(bulk_api, status, policy):
facade, create_request, _, _, send = bulk_api
send.side_effect = [
response({"code": status, "message": "Gateway failure"}, status=status),
response(outcomes(policy)),
]

with pytest.raises(APIError, match="Gateway failure"):
facade.create_many([create_request], on_conflict=policy)

assert send.call_count == 1


@pytest.mark.parametrize("body", [b"", b"null"])
def test_bulk_create_rejects_empty_response(bulk_api, body):
facade, create_request, endpoint, _, send = bulk_api
send.return_value = response(None)
send.return_value._content = body

with pytest.raises(RuntimeError, match=f"No response from /{endpoint}/createMany"):
facade.create_many([create_request])

assert send.call_count == 1


def test_bulk_create_rejects_swallowed_client_error(bulk_api):
facade, create_request, endpoint, _, send = bulk_api
send.side_effect = ValueError("Unexpected client failure")

with pytest.raises(RuntimeError, match=f"No response from /{endpoint}/createMany"):
facade.create_many([create_request])

assert send.call_count == 1
Loading
Loading