Skip to content

Fixes 32946: Pin entity repository lifecycle and cache contracts (1/7) - #33344

Open
harshach wants to merge 4 commits into
mainfrom
harshach/entity-stack-01-contracts
Open

harshach wants to merge 4 commits into
mainfrom
harshach/entity-stack-01-contracts

Conversation

@harshach

@harshach harshach commented Sep 15, 2026 •

Copy link
Copy Markdown
Collaborator

Describe your changes:

Part of #32946 — 1/7 in the compatible repository stack, preserving the existing public/protected facade.

Pins stored JSON, history, events, search visibility, Redis recovery and transaction replay before extraction, with a source-size/hook/import ratchet and 64 baseline fixtures; the existing CSV multi-node test runs in the isolated Maven lane.

Type of change:

  • Improvement

High-level design:

Base: main · Next: harshach/entity-stack-02-parent-hydration · Merge in order, retarget/restack children after their parent merges; this head requires no successor code.

  • Production delta for this slice: +0/-0 lines, counting helpers; EntityRepository budget: 13730 lines
  • Existing single-transaction, nested retry/rollback, Redis and synchronous post-commit contracts retained
  • Full session diff, complete capabilities, remaining dependency migration, explicit request state and outbox consolidation remain follow-up work

Tests:

Use cases covered

Create/update/delete/restore, PATCH consolidation, CSV/import, immediate search visibility, cache corruption/read-write races, deadlock replay and enclosing rollback

Unit tests

  • 1 passed; 0 skipped; no failures/errors — focused selection
  • Whole-class production coverage: not applicable — this slice changes tests and Maven test placement only

Backend integration tests

  • PostgreSQL/OpenSearch/Redis: 27 passed, 1 assumption-aborted, no failures
  • Added/updated tests: EntityCacheRecoveryIT, EntityRepositoryGoldenIT, OneTransactionFlushAtomicityIT, EntityRepositorySizeBudgetTest

Ingestion integration tests

Not applicable — no ingestion code changes

Playwright / UI recording

Not applicable — no UI changes

Manual testing performed

Automated local container executions above; no manual UI testing

Reproduce after building the backend and compiling ITs:

mvn -pl openmetadata-integration-tests -Ppostgres-opensearch -DcacheProvider=redis \
  -Dit.test=EntityRepositoryGoldenIT,EntityCacheRecoveryIT,OneTransactionFlushAtomicityIT,CsvExportMultiNodeIT \
  failsafe:integration-test@parallel-tests failsafe:verify

Checklist:

  • Issue linked as a partial step; the umbrella issue remains open
  • Java 21 service and integration-test compilation; Spotless apply/check
  • Focused behavior checks for this exact head
  • No production API change
  • Full required regression/CI and coverage gates (production coverage not applicable)
  • Calibrated API latency/load/allocation acceptance (no runtime change in this slice)

Draft: coverage and performance acceptance are incomplete, and the earlier combined artifact's broad RDF failure remains unresolved; focused passing results do not replace those gates.

Tested head: 56738eb64ab736a8ba6cc5e0aeb3961582ae064f · Native artifact SHA-256: b4c3842120113c08ab73db2c997654d6a8377b6cd3e980967fe24c27d9e004a7

RetriggerConfidence Score: 4/5

The PR is not ready to merge because its new backend integration tests and helper methods still violate explicit repository requirements for concurrent execution and focused method size.

Findings

  1. P2 Tests Violate Concurrency Requirement ▶
  2. P2 Import Method Is Overloaded ▶
  3. P2 Snapshot Method Does Too Much ▶
Summary

This PR adds integration-test baselines for entity repository lifecycle, cache recovery, transaction replay, and immediate search visibility, while moving the CSV multi-node test into isolated Maven lanes and adding repository source-size and extension-surface ratchets.

  • Adds golden lifecycle fixtures for tables, glossary terms, users, and test cases.
  • Exercises Redis corruption recovery and cache read/write races.
  • Expands deadlock replay assertions to owners and domains.
  • Makes golden-event ordering deterministic using the durable change-event offset.
  • Counts repository hook/import declarations by signature rather than method name.

Reviews (4) · Last reviewed commit: "Address review: event order, generation ..."

@github-actions github-actions Bot added backend safe to test Add this label to run secure Github workflows on PRs labels Sep 15, 2026
@harshach
harshach marked this pull request as ready for review September 18, 2026 14:49
@harshach
harshach requested a review from a team as a code owner September 18, 2026 14:49
@github-actions

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

This PR cannot be merged until the following are addressed on its linked issue:

  • No GitHub issue is linked. Link an issue in the Development section of the PR (or add Fixes #12345 to the description). For a same-org cross-repo issue, add Fixes open-metadata/<repo>#123 to the description.

The fields live on the linked issue in the Shipping project (open the issue → right sidebar → Projects). After you set them, re-run this check (or push a commit) — issue/project changes do not re-trigger it automatically.

Maintainers can bypass this check by adding the skip-pr-checks label.

import org.openmetadata.service.util.AsyncService;
import org.openmetadata.service.util.AsyncService.DatabaseOperation;

@Isolated("Captures lifecycle state and events without concurrent catalog mutation")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Tests Violate Concurrency Requirement

This new backend API integration test uses @Isolated, as does EntityCacheRecoveryIT, instead of the repository-required @Execution(ExecutionMode.CONCURRENT) model with namespace isolation. The global logger and cache manipulation should be redesigned so both tests can run concurrently. This explicit repository requirement must be satisfied before merging.

Context Used: CLAUDE.md (source)

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.

Not taking this one, with reasoning.

@Isolated is not a deviation here — it is a first-class category in this repo. 29 ITs under
it/tests/ already use it, and the build has a dedicated lane for exactly this
(integration-lane-global-state, with integrationTests.skipIsolated toggled per profile).

The reason it is required rather than preferred for these two: they mutate process-global JDBI
state
, not catalog data. SqlQueryCounter calls jdbi.setSqlLogger(this) and the cache test
manipulates the shared Redis-backed cache. Namespace isolation, which is what
@Execution(CONCURRENT) relies on in this repo, partitions data — it does nothing for a
singleton logger that every other test's SQL flows through. Run these concurrently and they replace
each other's logger and count each other's statements.

The suggestion to "redesign so both can run concurrently" would mean removing the global-logger
decoration, which is the measuring instrument the whole suite depends on — a SQL counter that does
not intercept the shared Jdbi cannot count anything.

Worth noting the concurrency guidance is satisfied where it applies: both tests use
TestNamespaceExtension and namespace-scoped fixtures, so they isolate their data as well as their
process state.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

You're right. @Isolated is appropriate here and my concurrency finding does not hold.

SqlQueryCounter replaces the process-global JDBI SqlLogger, so namespace isolation cannot make concurrent instances independent: concurrent tests can overwrite each other's logger, counts, and restoration target. The cache recovery test also exercises shared cache state, while TestNamespaceExtension still provides the necessary catalog-data isolation. The dedicated isolated/global-state Maven lane is the correct mechanism for this category of tests.

I withdraw this finding; no redesign to @Execution(CONCURRENT) is required.

Comment on lines +341 to +370
private void importCsv() throws IOException {
final EntityRepository<?> repository = Entity.getEntityRepository(kind.type);
final JsonNode entity = call(HttpMethod.GET, path() + "?fields=*", null);
final String scope =
switch (kind) {
case TABLE -> entity.path("fullyQualifiedName").asText();
case GLOSSARY_TERM -> entity.path("glossary").path("fullyQualifiedName").asText();
case USER -> entity.path("teams").get(0).path("fullyQualifiedName").asText();
case TEST_CASE -> entity.path("entityFQN").asText();
};
final var exporter =
kind == Kind.GLOSSARY_TERM ? Entity.getEntityRepository(Entity.GLOSSARY) : repository;
final String csv = withCsvDescription(exporter.exportToCsv(scope, "admin", false));
final var result =
kind == Kind.TEST_CASE
? repository.importFromCsv(scope, csv, false, "admin", false, Entity.TABLE)
: exporter.importFromCsv(scope, csv, false, "admin", false);
assertEquals(0, result.getNumberOfRowsFailed(), result.getImportResultsCsv());
assertEquals(1, result.getNumberOfRowsPassed(), result.getImportResultsCsv());
// CSV currently persists its events asynchronously; snapshot the completed event contract.
final var async = AsyncService.getInstance();
Awaitility.await()
.atMost(Duration.ofSeconds(10))
.during(Duration.ofMillis(100))
.until(
() ->
async.getOperationQueuedCount(DatabaseOperation.CSV_CHANGE_EVENT) == 0
&& async.getOperationActiveCount(DatabaseOperation.CSV_CHANGE_EVENT) == 0);
capture("csv-import");
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Import Method Is Overloaded

importCsv combines scope resolution, repository selection, export mutation, import dispatch, assertions, asynchronous synchronization, and snapshotting in one roughly 30-line method. This violates the Java guide requiring methods to stay around 15 lines and perform one nameable task. Extract the scope/import and event-drain operations; the new bulkCreate and withCsvDescription methods have the same pattern. This repository requirement must be satisfied before merging.

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

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.

Partly taken.

importCsv is shorter — the event-drain it used to inline is now awaitEvents in
EntityGoldenSnapshot, extracted for correctness (verification and generation need different wait
conditions) rather than for length.

I have not split scope resolution from import dispatch. The method reads as one nameable task —
"import this CSV and capture the result" — and the intermediate steps are not independently
meaningful: a resolveScope returning something only importCsv can use would add a name without
adding a seam. bulkCreate and withCsvDescription are in the same position.

The Java guide's ~15 lines is a guideline against methods doing several jobs, and the test for that
is whether the parts can be named and used separately. Here they cannot, so splitting would trade a
readable sequence for indirection. Worth a maintainer's call if you disagree.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

That’s fair. Extracting awaitEvents addresses the concrete synchronization concern, and I agree that a resolveScope helper used only by this flow would add a name without creating a useful seam. On review, importCsv is a coherent scenario operation—export, modify, import, assert, and capture—so the ~15-line guidance should not be treated as a hard gate here. I’m withdrawing this finding; no further split is required for importCsv, bulkCreate, or withCsvDescription based on method length alone.

Comment on lines +43 to +79
final JsonNode expected = readFixture(name);
final var repository = Entity.getEntityRepository(type);
final ObjectNode state = JsonUtils.getObjectNode();
final var jdbi = Entity.getJdbi();
final List<String> stored =
jdbi.withHandle(
handle ->
handle
.createQuery(
"SELECT json FROM "
+ repository.getDao().getTableName()
+ " WHERE id = :id")
.bind("id", id.toString())
.mapTo(String.class)
.list());
final List<String> history =
jdbi.withHandle(
handle ->
handle
.createQuery(
"SELECT json FROM entity_extension WHERE id = :id AND extension LIKE :prefix ORDER BY extension")
.bind("id", id.toString())
.bind("prefix", type + ".version.%")
.mapTo(String.class)
.list());
// EventFilter delivers asynchronously, independently of the synchronous entity write.
final List<JsonNode> events =
Awaitility.await()
.pollDelay(Duration.ZERO)
.atMost(Duration.ofSeconds(10))
.until(
() -> events(type, id),
rows -> expected == null || rows.size() >= expected.path("events").size());
state.set("stored", JsonUtils.valueToTree(stored.stream().map(JsonUtils::readTree).toList()));
state.set("history", JsonUtils.valueToTree(history.stream().map(JsonUtils::readTree).toList()));
state.set("events", JsonUtils.valueToTree(events));
assertFixture(name, expected, normalize(state));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Snapshot Method Does Too Much

assertMatches combines fixture loading, two database queries, asynchronous polling, state assembly, normalization, and assertion in one long method. This violates the Java guide requiring methods to stay around 15 lines and perform one nameable task. Split state capture from fixture comparison; the new normalizeText method similarly mixes embedded-JSON parsing, alias replacement, and identifier normalization. This repository requirement must be satisfied before merging.

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

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.

Partly taken.

assertMatches is shorter now: the event wait moved into awaitEvents, which also separates
verification (wait for the pinned count) from generation (wait for quiescence) — a split that was
needed for correctness, not only length. See the thread on line 87.

I have not split state capture from fixture comparison. The three reads — stored row, version
history, events — have to be taken as one consistent observation of the entity before anything is
compared; separating capture from comparison would either widen the window between them or require
passing the partial state around, which reads worse than the sequence it replaces. normalizeText
is similarly left alone: embedded-JSON parsing, alias replacement and id normalisation are three
steps of one transform on one value, and naming them apart would not make the transform easier to
follow.

Happy to revisit if a reviewer disagrees on the second half.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The consistency concern is fair, but extracting capture would not widen the observation window or require passing partial state. A captureState helper can perform the same stored-row, history, and event reads in the same order, assemble the complete ObjectNode, and return it; assertMatches can then load the fixture, call that helper, normalize, and compare. In fact, the current three reads are already on separate Jdbi handles, and events are awaited after the first two reads, so the existing method is not an atomic snapshot that extraction would weaken.

I agree normalizeText is cohesive enough to keep as one transformation. The capture/comparison split is still worthwhile for EntityGoldenSnapshot.java:58: it leaves the assertion method focused on orchestration and comparison without changing read ordering or behavior.

@harshach
harshach added this pull request to stack #33585 September 18, 2026 14:57

@mohityadav766 mohityadav766 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Review: entity repository lifecycle and cache contracts (1/7)

Reviewed at a74c47d. No production code changes, so the risk here is confined to whether the new baseline actually pins what it claims to. Most of what follows is about that: several scenarios currently assert less than they appear to, and a few are non-deterministic in ways that will show up as CI flakes rather than as real regressions.

Grouping the 15 inline comments:

Determinism of the baseline (will flake or has already drifted)

  1. Fixture generation short-circuits the event wait (expected == null), so baselines are recorded by an unwaited path and checked by a waited one.
  2. Event ordering ties on millisecond eventTime; change_event.offset would give a total order.
  3. Text beginning with { or [ is re-parsed as JSON and throws.

The new a74c47d commit — pinning ISO dates so fixtures survive a calendar rollover — is a good instance of exactly this class of problem, and I think there are a few more of the same shape still open.

Scenarios that assert less than they look like they do
4. rename silently no-ops for table, user and testCase — those three rename.json files are byte-equivalent in shape to patch-noop.json, and patch-after-rename is therefore mislabelled. The rename-denied branch also has no committed fixture.
5. csv-import pins a column-description change that produced no version bump and no change event — worth a comment if that audit gap is known.
6. The cache-recovery "next read serves from cache" assertion is satisfied by the L1 Caffeine layer, not the Redis repair it names.
7. The final cache post-condition is skipped entirely when the entry is absent (orElse("{}") + if (value.has("id"))).

Ratchet strength — the EntityRepositorySizeBudgetTest gates can pass while measuring nothing (null compiler, unchecked relative source path, discarded parse diagnostics), and the hook/import budgets key on bare method names so overloads do not count against them.

Concurrency — SqlQueryCounter publishes this as the global JDBI logger before setting its non-volatile trigger fields, which are then read from server request threads via the RequestLatencyContext predicate.

Smaller items — an IndexOutOfBoundsException on short CSV rows, a get(0) NPE on teams, one duplicated DAO query, and two .claude/rules/java.md violations (a fully-qualified Assertions.assertTrue, and raw event-type literals where the generated EventType enum exists).

Worth saying plainly: I verified the production APIs these tests reach for (AsyncService.getOperationQueuedCount, CachedEntityDao, EntityRepository.CACHE_WITH_ID, createMany, createOrUpdateForImport, the CSV overloads) and they all line up, and the pom.xml lane move is symmetric across all eight profile include/exclude pairs. I also checked the http://localhost:8585 hrefs baked into the fixtures — those are not a port-binding bug, since the IT server binds port: 0 but RestUtil.getHref prefers the OPEN_METADATA_BASE_URL_CONFIGURATION setting over the request URI. They do couple all 64 fixtures to that global setting, which is worth knowing.

I have not run the suite; findings are from reading the diff, the enclosing code, and the committed fixtures.

🤖 Generated with Claude Code

.atMost(Duration.ofSeconds(10))
.until(
() -> events(type, id),
rows -> expected == null || rows.size() >= expected.path("events").size());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixture generation captures events with zero wait

In generation mode readFixture returns null (line 126), so this predicate is true on its first evaluation, and pollDelay(Duration.ZERO) removes the initial delay. Generation therefore snapshots whatever change_event rows happen to exist at t=0 — while the comment two lines up says delivery is asynchronous.

The 64 committed fixtures were produced by the unwaited path and are checked by the waited one. If a baseline was recorded while the last entityUpdated was still in flight, it pins N events; the next verification run polls, sees N+1 (>= N, so the predicate passes), and assertEquals on line 142 fails on the full-state diff.

Suggest having generation wait on the same quiescence signal the CSV scenario already uses, rather than short-circuiting on expected == null.

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.

Valid — fixed in 8739d22.

Generation took the expected == null short-circuit, so with pollDelay(Duration.ZERO) the
predicate was true on its first evaluation and the baseline captured whatever had committed at t=0.
Every one of the 64 fixtures was produced that way and is checked by the waited path, which is
exactly the asymmetry you describe.

Generation now waits for quiescence instead — two consecutive polls returning the same count:

final AtomicInteger previous = new AtomicInteger(-1);
return Awaitility.await()
    .pollDelay(Duration.ZERO)
    .pollInterval(Duration.ofMillis(250))
    .atMost(Duration.ofSeconds(30))
    .until(() -> events(type, id),
           rows -> !rows.isEmpty() && rows.size() == previous.getAndSet(rows.size()));

The !rows.isEmpty() guard is there because "quiet" and "nothing has arrived yet" are the same
reading at t=0; every captured step follows a write that produces at least one event for the entity.

Verification keeps the >= expected wait. The two paths are now separate branches of one
awaitEvents method rather than one predicate with a null special case.

.map(JsonUtils::readTree)
.filter(event -> id.toString().equals(event.path("entityId").asText()))
.sorted(
Comparator.comparingLong((JsonNode event) -> event.path("timestamp").asLong())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Event ordering is ambiguous for same-millisecond events

ORDER BY eventTime (line 100) plus this stable sort on timestamp and the 5-value eventOrder rank leaves consecutive updates tied: all entityUpdated events map to default -> 1.

table/hard-delete.json pins 9 events, five of them consecutive entityUpdated with different currentVersion payloads. Two written inside the same millisecond keep an arbitrary DB-returned order, so the fixture flips between runs.

change_event has a monotonic offset column that gives a total, stable order — it is already used that way in AccessControlDAOs.java:1113.

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.

Valid — fixed in 8739d22, using the offset column you pointed at.

ORDER BY eventTime plus a rank where every entityUpdated fell to default -> 1 left consecutive
updates genuinely tied, and table/hard-delete.json pinning five in a row made that a live coin
flip rather than a theoretical one.

"SELECT json FROM change_event WHERE entityType = :type ORDER BY " + offsetColumn() + " ASC"

offset is reserved in both dialects and quoted differently, so the column name is chosen from
DatasourceConfig.getInstance().isMySQL() — backticks on MySQL, double quotes on Postgres — the
same split AccessControlDAOs makes with @ConnectionAwareSqlQuery.

The Java re-sort is gone entirely: offset is a total order, so there is nothing left to
disambiguate. That also retires the eventOrder switch, which the bot separately flagged for using
raw event-type literals — the fix for one removed the other.

capture(name);
}

private void rename(String name) throws IOException {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

rename silently no-ops for 3 of 4 kinds, and nothing asserts otherwise

This method handles only an explicit 400 rejection and never asserts the name actually changed. Comparing the committed fixtures:

kind rename.json name version events same as patch-noop.json?
glossaryTerm golden_renamed 0.3 5 no — real rename
table golden_entity 0.2 4 yes
user golden_entity 0.2 4 yes
testCase golden_entity 0.4 4 yes

For table, user and testCase the PATCH returns 200 and is silently ignored, so rename and the following patch-after-rename are duplicates of patch-noop and would not detect a rename regression. That case falls through the success path, which the catch (OpenMetadataException) branch does not cover.

Separately, capture("rename-denied") on line 325 has no committed fixture, so if a kind ever does start returning 400 the test fails with Missing baseline fixture: /entity-repository-golden/<type>/rename-denied.json rather than something diagnostic.

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.

Valid, and the table row in your comparison turned out to be the interesting one.

Fixed in 8739d22: Kind now declares renameAllowed (true only for GLOSSARY_TERM) and
the outcome is asserted per kind — honoured when allowed, explicitly not honoured otherwise. A
kind that starts or stops honouring renames now fails here instead of quietly changing what the
fixture means. The capture("rename-denied") path is gone; nothing reaches it, since the PATCH
returns 200 rather than 400.

I read renameAllowed from the test's own enum rather than the repository: the field is
protected with no getter, and adding one would widen the very surface this PR freezes — it would
also move the hook budget.

On deleting the fixtures — I was about to drop rename.json for the three kinds as dead
duplicates, and checked first. user and testCase are byte-identical to patch-noop.json, as you
said. table is not:

- "fullyQualifiedName": "service.database.schema.golden_entity.id"
+ "fullyQualifiedName": "service.database.schema.golden_renamed.id"

That is stored[0].columns[0] — the persisted row. The table kept golden_entity, and a child
column's FQN was rebuilt from the name the repository rejected. So the rename is not a no-op for
Table; it half-applies and leaves the column claiming a parent that does not exist under that name.

So the capture stays for every kind. "The name was rejected" is not "nothing was written", and this
fixture is the only thing recording that. I'll raise the column-FQN inconsistency as its own issue
rather than change main's behaviour inside a baseline PR — flagging it here first in case you read
it differently.


public static SqlQueryCounter deadlockOnce(final Jdbi jdbi, final String fragment) {
final var counter = forRequests(jdbi, fragment);
counter.deadlockAfterFirst = true;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Deadlock flag is set after this escapes to other threads

The constructor publishes this as the global JDBI logger (jdbi.setSqlLogger(this), line 57) and only then does this line set the trigger. afterFirst (line 48) has the same shape. Neither field is volatile, yet forRequests scopes matching to RequestLatencyContext.getContext() != null (line 36) — any server request thread.

A request already in flight when EntityRepositoryGoldenIT.replayPatch arms the counter runs update table_entity, gets counted by logBeforeExecution, but reads the stale deadlockAfterFirst == false. No deadlock is injected; the real patch's first write is then count == 2 and never deadlocks, so assertEquals(2, writes.count(), "One rolled-back write and one committed replay") fails. The inverse also happens — the injected RuntimeException fires inside an unrelated request.

The deadlockAfterFirst = false reset on line 93 is likewise a non-atomic check-then-act. Setting both fields before setSqlLogger, and making them volatile (or an AtomicBoolean), would close this.

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.

Valid — fixed in 8739d22.

Both triggers were assigned after the constructor published this via jdbi.setSqlLogger(this),
and forRequests admits any thread with a RequestLatencyContext, so the race you describe is
reachable in both directions: an in-flight request consuming the count while still reading
deadlockAfterFirst == false, or the injected exception surfacing inside an unrelated request.

Two changes:

  • Set before publication. The triggers move into the constructor, and setSqlLogger(this) is
    the last statement — every field is visible before any other thread can reach the logger.
  • Atomic, and fire-once by CAS rather than check-then-act. AtomicBoolean /
    AtomicReference, with deadlockAfterFirst.compareAndSet(true, false) and
    afterFirst.getAndSet(null) replacing the read-then-clear pairs — two in-scope statements can
    arrive together and the trigger must fire exactly once.

Worth flagging for the merge order: this class also exists in #33355 (byte-identical to this copy)
and, with the probe split out, in #33539. The plan is for #33539 to become the single source and for
this PR and #33355 to drop their copies on rebase — #33539's version keeps the same
Predicate<StatementContext> scoping taken from here, and moves injection into SqlFailureProbe
where the one-shot claim is already a compareAndSet. This fix keeps the copy correct standalone in
the meantime.


private static void collectMethods(Path source, Set<String> hooks, Set<String> imports)
throws IOException {
final var compiler = ToolProvider.getSystemJavaCompiler();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The ratchet passes vacuously when parsing yields nothing

Three gaps let this test report green while measuring zero methods:

  • ToolProvider.getSystemJavaCompiler() returns null on a JRE — NPE on the next line rather than a skip.
  • sourcePath() (lines 38-44) guesses two working-directory-relative paths and returns the second unchecked if neither is a regular file.
  • compiler.getTask is passed a null DiagnosticListener (line 53), so parse errors are discarded. If parse() yields no compilation units, hooks and imports stay empty and both assertTrue(... <= BUDGET) assertions pass.

Since the point of this file is to be a ratchet, it is worth asserting that the source resolves and that the collected counts are non-zero — otherwise moving or splitting EntityRepository.java quietly disarms it.

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.

Valid — all three gaps closed in 8739d22.

assertNotNull(compiler, "A JDK is required to parse EntityRepository; this is running on a JRE");
...
assertTrue(Files.isRegularFile(resolved),
    () -> "EntityRepository source not found at " + resolved.toAbsolutePath());
...
assertTrue(diagnostics.getDiagnostics().stream().noneMatch(d -> d.getKind() == Diagnostic.Kind.ERROR), ...);
assertEquals(1, units, "Expected exactly one compilation unit");
assertFalse(hooks.isEmpty(), "Parsed no protected hooks — the ratchet is measuring nothing");
assertFalse(imports.isEmpty(), "Parsed no *ForImport methods — the ratchet is measuring nothing");

A DiagnosticCollector now replaces the null listener on both getStandardFileManager and
getTask, so a parse error fails loudly instead of yielding zero units and satisfying every upper
bound. Your framing was the useful part: the failure mode is not "the test breaks", it is "the test
reports green while measuring nothing", which is the one outcome a ratchet must never have.

? repository.importFromCsv(scope, csv, false, "admin", false, Entity.TABLE)
: exporter.importFromCsv(scope, csv, false, "admin", false);
assertEquals(0, result.getNumberOfRowsFailed(), result.getImportResultsCsv());
assertEquals(1, result.getNumberOfRowsPassed(), result.getImportResultsCsv());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The csv-import baseline pins a mutation with no audit event

For Kind.TABLE, table/csv-import.json differs from table/import-update.json in exactly one value: columns[0].description goes null -> "csv". Everything else is identical — version stays 0.3, history stays at 2 entries, events stays at 5 with the same event types.

So the import mutated persisted state without bumping the version or emitting an entityUpdated event, while this assertion reports one row passed. Two consequences:

  1. The scenario's events / history sections assert nothing that import-update did not already assert, and the AsyncService drain on lines 361-368 waits for events that never arrive.
  2. The baseline now blesses that audit gap as reference behaviour with no comment or linked issue.

If this is known and intended, a comment in the fixture-producing scenario would keep the next reader from treating it as verified coverage.

}

private String normalizeText(String value) {
if (value.startsWith("{") || value.startsWith("[")) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Any text starting with { or [ is re-parsed as JSON

This branches purely on a leading brace or bracket, so ordinary prose crashes the capture rather than producing a diff. A description, displayName or CSV-imported value such as {{macro}}, [draft] revenue table or []cleanup is not valid JSON, and JsonUtils.readTree throws out of normalize.

Today's fixtures only survive because every description is a bare word (created, put, patch). The helper is generic and applied to every string in stored/history/event payloads, so this will surface the first time a scenario uses realistic text. Keying off the field name (entity, json) would be more predictable than sniffing the first character.

handle ->
handle
.createQuery(
"SELECT json FROM entity_extension WHERE id = :id AND extension LIKE :prefix ORDER BY extension")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This duplicates the existing EntityExtensionDAO.getExtensions

CoreRelationshipDAOs.EntityExtensionDAO.getExtensions(UUID id, String extensionPrefix) already runs:

SELECT extension, json FROM entity_extension
WHERE id = :id AND extension LIKE CONCAT(:extensionPrefix, '.%')
ORDER BY extension

— the same query, including the .% prefix convention and the ordering. Hand-rolling it means the fixture harness drifts silently if the version-extension naming or ordering ever changes in production.

Lines 64-66 similarly concatenate repository.getDao().getTableName() into a raw SQL string; Entity.getCollectionDAO() already exposes typed accessors for both reads.

final var headers = records.getFirst().toList();
final int description =
headers.indexOf(kind == Kind.TABLE ? "column.description" : "description");
org.junit.jupiter.api.Assertions.assertTrue(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fully-qualified name where an import is expected

.claude/rules/java.md (scoped to **/*.java) states: "No fully-qualified names in code — import the class instead."

This file already static-imports assertEquals from the same class on line 3, so assertTrue can join it.


private static int eventOrder(JsonNode event) {
// Hard deletion reuses the last entity timestamp, so SQL timestamp order alone is ambiguous.
return switch (event.path("eventType").asText()) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Raw event-type literals instead of the generated enum

.claude/rules/java.md states: "Never raw string literals in .equals()/.contains()/switch — use a constant or existing enum (prefer enums from openmetadata-spec/ schemas for closed sets)" and "If a string appears in more than one place it must be a named constant, defined once."

This switch uses "entityCreated" / "entitySoftDeleted" / "entityRestored" / "entityDeleted" rather than the generated EventType enum, so a schema rename still compiles and silently reorders every fixture.

Same rule elsewhere in the PR: "admin" appears 4x in EntityRepositoryGoldenIT (lines 338, 353, 356, 357); "from table_entity" (3x) and "committed during read" (4x) are repeated in EntityCacheRecoveryIT.

harshach and others added 2 commits September 18, 2026 13:43
The budgets only asserted actual <= budget, so shrinking EntityRepository left
the constants untouched and the headroom available for the next PR to spend
without review noticing. Each metric now also asserts actual >= budget - slack,
which forces a PR that shrinks the class to lower the constant in the same diff.

Slack is 50 lines because line counts move a little on edits that are not
extractions - a reformat, an added import. Hooks and *ForImport methods are sets
of distinct names, so their lower bound is exact.

The lower bound matters most for the hook count. #28778 "shrank" this class by
moving code into collaborators that kept a back-reference, which reduces lines
while leaving the coupling surface where it was. An upper bound alone records
that as progress; a bound that must be lowered to match forces the question of
whether the surface actually shrank.

Budgets are unchanged and match today exactly: 13730 lines, 141 hooks, 13
*ForImport. Verified both directions - green as committed, and raising a budget
above the measured value now fails with "Protected hooks fell to 141, below the
budget of 142. Lower the constant to 141 in this same diff."

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
… CSV, counter

Seven correctness findings from @mohityadav766 and the bot, all valid.

Event ordering (33344#4049561028). events() ordered by eventTime and re-sorted
on a 5-value bucket where every entityUpdated mapped to the same rank, so
consecutive updates in one millisecond kept an arbitrary DB order -
table/hard-delete.json pins five in a row. Now ordered by the change_event
`offset` sequence, quoted per dialect. That also retires the event-type string
switch the bot flagged separately.

Generation-mode waiting (33344#4049561014). readFixture returns null when
generating, so the Awaitility predicate was true on its first poll and the
baseline captured whatever had committed at t=0. Generation now waits for
quiescence - two consecutive polls with the same event count - instead of
short-circuiting on "no expectation".

Budget keying (33344#4049561068). hooks and imports were Set<String> of method
names, so an overload of an existing protected hook cost nothing. Now keyed on
the erased signature; the same source measures 171 hooks and 19 *ForImport
declarations against 141 and 13 names, meaning 30 protected overloads and 6
import overloads were invisible. Budgets updated to the numbers that cannot be
gamed.

Ratchet could pass vacuously (33344#4049561058). Asserts the compiler is a JDK,
that the source path resolves, that exactly one compilation unit parsed with no
error diagnostics, and that the collected sets are non-empty.

rename (33344#4049561036). Only GlossaryTerm allows it; for the others the
PATCH returns 200 and the name is put back, so the fixture was
indistinguishable from patch-noop. Kind now declares renameAllowed and the
outcome is asserted per kind. The capture stays, because "name rejected" is not
"nothing written": table/rename.json records a column whose
fullyQualifiedName was rebuilt from the rejected name while the table kept the
old one. Filed separately. The unreachable rename-denied capture is gone.

CSV row width (33344#4049561076). Commons CSV does not pad short records, so
values.set(description, "csv") could throw IndexOutOfBoundsException. Rows are
padded to header width first.

SqlQueryCounter publication (33344#4049561049). deadlockAfterFirst and
afterFirst were assigned after the constructor published `this` as the global
SQL logger, and read unsynchronised from any request thread. Both are now set
before publication and hold atomics, and the fire-once paths use getAndSet /
compareAndSet instead of check-then-act.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Comment on lines +326 to +340
/**
* Renames the entity, for the kinds that allow it.
*
* <p>Only GlossaryTerm sets {@code renameAllowed}. For Table, User and TestCase the PATCH
* returns 200 and the new name is silently ignored, so capturing a "rename" fixture for them
* recorded a duplicate of patch-noop that could never detect a rename regression. The
* post-condition is asserted rather than assumed: a kind that starts honouring or rejecting a
* rename has to be dealt with here instead of quietly changing what the baseline means.
*/
/**
* Renames the entity and pins the outcome, which differs by kind.
*
* <p>Only GlossaryTerm sets {@code renameAllowed}. For the others the PATCH still returns 200
* and {@code EntityRepository:1325} puts the original name back, so without an assertion the
* captured fixture is indistinguishable from patch-noop and could never detect a rename

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Quality: Duplicate Javadoc block left on rename() method

The rename method now carries two consecutive Javadoc blocks (lines 326-334 and 335-344), both documenting the same method. This appears to be a merge/edit artifact — the earlier revision's comment was not removed when the replacement was added. Only the second block (immediately preceding the declaration) is the effective Javadoc; the first is dead comment text that duplicates and slightly contradicts it. Delete the first block so the method has a single description.

Remove the first, redundant Javadoc block, keeping the single accurate description.:

/**
 * Renames the entity and pins the outcome, which differs by kind.
 *
 * <p>Only GlossaryTerm sets {@code renameAllowed}. For the others the PATCH still returns 200
 * and {@code EntityRepository:1325} puts the original name back, so without an assertion the
 * captured fixture is indistinguishable from patch-noop and could never detect a rename
 * regression. The fixture is still captured for every kind, because "the name was rejected"
 * does not mean "nothing was written": {@code table/rename.json} records a column whose
 * fullyQualifiedName was rebuilt from the rejected name while the table kept the old one.
 */
private void rename(String name) throws IOException {
  • Apply fix

Check the box to apply the fix or reply for a change | Was this helpful? React with 👍 / 👎

@gitar-bot

gitar-bot Bot commented Sep 19, 2026

Copy link
Copy Markdown
Code Review 👍 Approved with suggestions 0 closed / 1 findings

🟢 Low risk

Adds comprehensive golden fixtures and integration tests pinning entity repository lifecycle, persistence, event ordering, search visibility, cache recovery, and transaction replay behavior. Minor issue: duplicate Javadoc block on the rename() method should be removed to leave a single description.

💡 Quality: Duplicate Javadoc block left on rename() method

📄 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/EntityRepositoryGoldenIT.java:326-340

The rename method now carries two consecutive Javadoc blocks (lines 326-334 and 335-344), both documenting the same method. This appears to be a merge/edit artifact — the earlier revision's comment was not removed when the replacement was added. Only the second block (immediately preceding the declaration) is the effective Javadoc; the first is dead comment text that duplicates and slightly contradicts it. Delete the first block so the method has a single description.

Remove the first, redundant Javadoc block, keeping the single accurate description.
/**
 * Renames the entity and pins the outcome, which differs by kind.
 *
 * <p>Only GlossaryTerm sets {@code renameAllowed}. For the others the PATCH still returns 200
 * and {@code EntityRepository:1325} puts the original name back, so without an assertion the
 * captured fixture is indistinguishable from patch-noop and could never detect a rename
 * regression. The fixture is still captured for every kind, because "the name was rejected"
 * does not mean "nothing was written": {@code table/rename.json} records a column whose
 * fullyQualifiedName was rebuilt from the rejected name while the table kept the old one.
 */
private void rename(String name) throws IOException {
🤖 Prompt for agents
Code Review: Adds comprehensive golden fixtures and integration tests pinning entity repository lifecycle, persistence, event ordering, search visibility, cache recovery, and transaction replay behavior. Minor issue: duplicate Javadoc block on the `rename()` method should be removed to leave a single description.

1. 💡 Quality: Duplicate Javadoc block left on rename() method
   Files: openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/EntityRepositoryGoldenIT.java:326-340

   The `rename` method now carries two consecutive Javadoc blocks (lines 326-334 and 335-344), both documenting the same method. This appears to be a merge/edit artifact — the earlier revision's comment was not removed when the replacement was added. Only the second block (immediately preceding the declaration) is the effective Javadoc; the first is dead comment text that duplicates and slightly contradicts it. Delete the first block so the method has a single description.

   Fix (Remove the first, redundant Javadoc block, keeping the single accurate description.):
   /**
    * Renames the entity and pins the outcome, which differs by kind.
    *
    * <p>Only GlossaryTerm sets {@code renameAllowed}. For the others the PATCH still returns 200
    * and {@code EntityRepository:1325} puts the original name back, so without an assertion the
    * captured fixture is indistinguishable from patch-noop and could never detect a rename
    * regression. The fixture is still captured for every kind, because "the name was rejected"
    * does not mean "nothing was written": {@code table/rename.json} records a column whose
    * fullyQualifiedName was rebuilt from the rejected name while the table kept the old one.
    */
   private void rename(String name) throws IOException {

Review coverage

Rules No rules evaluated

Functional validation Not enabled · Set up

Auto-approval Not enabled · Set up

Options

Display: compact → Counting what did not apply, without listing it.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Powered by Gitar — free for open source

This branch was previously deployed

1 inactive (outdated) deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend safe to test Add this label to run secure Github workflows on PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants