This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/main/pr-9636-a038371b620f67e9aeb2c067f393f46169ac3331 in repository https://gitbox.apache.org/repos/asf/texera.git
commit c15f72498e10d0c0bade0fda859eb14437e5b732 Author: Meng Wang <[email protected]> AuthorDate: Mon Nov 23 19:59:22 2026 +0000 fix(storage): report a table as missing only when it does not exist (#9636) ### What changes were proposed in this PR? `IcebergUtil.loadTableMetadata` and the Python worker's `load_table_metadata` returned `None` for any failure, so a catalog that could not be read looked like a deleted table: result-service answered 404, or 200 with an empty page, and counts and reads came back empty. They now return `None` only when the table or its namespace does not exist, and raise anything else. `openDocument` throws `DocumentNotFoundException`, a subtype of the `IllegalArgumentException` it always threw, so callers match the type instead of the message. The three places that clear results (deleting a workflow, deleting executions, and clearing a workflow's previous execution) now share `clearDocument`, which passes over a missing document and logs any other failure. Two of them swallowed every failure, so a table that could not be cleared was left behind unnoticed. Expiring the runtime statistics' snapshots now handles failures the same way. One lookup stays best effort. Once an `IcebergDocument` iterator has returned every row of the table it resolved, it looks for rows committed since. Failing that should not fail a read that is complete, so it logs a warning and ends, as it did before. **Behavior change in the engine.** When the catalog fails as a reader first resolves its materialized input, the reader now fails instead of giving the operator no input. As when opening the document fails today, the JVM reader thread rethrows and the Python reader logs, and neither ends its channel, so the operator waits rather than producing a wrong result. ### Any related issues, documentation, discussions? Closes #9635. ### How was this PR tested? - Written first, and red on main: `ResultResourceSpec` answered 404 and 200 where it expects 500, `IcebergDocumentSpec` counted 0 and read empty, `IcebergUtilSpec` got `None`, and three Python cases did not raise. - `IcebergUtilSpec` pinned the old behavior ("return None when loading table metadata fails"). It now covers a missing table or namespace, and every other failure. - Removing the best-effort lookup turns its `IcebergDocumentSpec` case red. - `WorkflowExecutionsResourceSpec` covers `clearDocument`: dropping either branch, or the log, turns a case red. - The WorkflowCore suite (889 tests, on the rest and postgres catalogs), `ResultResourceSpec`, and, against a local Postgres, the amber unit suite (2443 tests) and the Python storage suite (144 tests) pass. scalafmt, scalafix and ruff are clean. ### Was this PR authored or co-authored using generative AI tooling? Generated-by: Claude Code (claude-opus-5-5) --- .../python/core/storage/iceberg/iceberg_utils.py | 9 +++- .../user/workflow/WorkflowExecutionsResource.scala | 35 ++++++++++--- .../dashboard/user/workflow/WorkflowResource.scala | 20 ++----- .../texera/web/service/WorkflowService.scala | 13 ++--- .../core/storage/iceberg/test_iceberg_document.py | 12 +++++ .../storage/iceberg/test_iceberg_utils_catalog.py | 26 +++++++++ .../workflow/WorkflowExecutionsResourceSpec.scala | 54 ++++++++++++++++++- .../texera/web/service/WorkflowServiceSpec.scala | 29 +++++++--- .../amber/core/storage/DocumentFactory.scala | 9 +++- .../storage/result/iceberg/IcebergDocument.scala | 21 +++++++- .../org/apache/texera/amber/util/IcebergUtil.scala | 13 +++-- .../amber/core/storage/DocumentFactorySpec.scala | 6 ++- .../storage/result/iceberg/FailingCatalog.scala | 36 +++++++++++++ .../result/iceberg/IcebergDocumentSpec.scala | 61 ++++++++++++++-------- .../apache/texera/amber/util/IcebergUtilSpec.scala | 25 +++++++-- .../texera/service/resource/ResultResource.scala | 3 +- .../service/resource/ResultResourceSpec.scala | 29 +++++++++- 17 files changed, 324 insertions(+), 77 deletions(-) diff --git a/amber/src/main/python/core/storage/iceberg/iceberg_utils.py b/amber/src/main/python/core/storage/iceberg/iceberg_utils.py index 63148598c3..9895c49261 100644 --- a/amber/src/main/python/core/storage/iceberg/iceberg_utils.py +++ b/amber/src/main/python/core/storage/iceberg/iceberg_utils.py @@ -24,6 +24,7 @@ import pyiceberg.table from fsspec.config import conf as fsspec_conf from pyiceberg.catalog import Catalog, load_catalog from pyiceberg.catalog.sql import SqlCatalog +from pyiceberg.exceptions import NoSuchNamespaceError, NoSuchTableError from pyiceberg.expressions import AlwaysTrue from pyiceberg.io.pyarrow import ArrowScan from pyiceberg.partitioning import UNPARTITIONED_PARTITION_SPEC @@ -293,7 +294,11 @@ def load_table_metadata( """ Loads metadata for an existing Iceberg table. - Returns the table if it exists and is successfully loaded. - - Returns None if the table does not exist or cannot be loaded. + - Returns None if the table, or its namespace, does not exist. + + Any other failure is raised, such as a catalog that cannot be reached. Taken + for a missing table, it would make a result that exists look deleted, or a + table read as empty. :param catalog: The Iceberg catalog to load the table from. :param table_namespace: The namespace of the table. @@ -303,7 +308,7 @@ def load_table_metadata( identifier = f"{table_namespace}.{table_name}" try: return catalog.load_table(identifier) - except Exception: + except (NoSuchTableError, NoSuchNamespaceError): return None diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResource.scala index febca649a9..c27561ca5e 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResource.scala @@ -19,13 +19,16 @@ package org.apache.texera.web.resource.dashboard.user.workflow +import com.typesafe.scalalogging.Logger import io.dropwizard.auth.Auth import org.apache.texera.amber.core.storage.{ DocumentFactory, + DocumentNotFoundException, ExecutionResultUris, FileResolver, WarehouseReadGuard } +import org.apache.texera.amber.core.storage.model.VirtualDocument import org.apache.texera.amber.core.tuple.Tuple import org.apache.texera.amber.core.virtualidentity._ import org.apache.texera.amber.core.workflow.GlobalPortIdentity @@ -56,8 +59,11 @@ import javax.ws.rs._ import javax.ws.rs.core.{MediaType, Response} import scala.collection.mutable import scala.jdk.CollectionConverters._ +import scala.util.control.NonFatal object WorkflowExecutionsResource { + private val logger: Logger = Logger(classOf[WorkflowExecutionsResource]) + private def context: DSLContext = SqlServer .getInstance() @@ -397,16 +403,29 @@ object WorkflowExecutionsResource { // Clear corresponding Iceberg documents. While per-user warehouses are disabled, // cleanup must not reach into them (#6930) — those URIs are skipped. - uris.filterNot(WarehouseReadGuard.skipWhileDisabled(_)).foreach { uri => - try { - DocumentFactory.openDocument(uri)._1.clear() - } catch { - case _: Throwable => - // Document already deleted – safe to ignore - } - } + uris + .filterNot(WarehouseReadGuard.skipWhileDisabled(_)) + .foreach(clearDocument(_)) } + /** + * Clears the document at `uri`, once the record that named it has been deleted. A document that + * is already gone needs nothing. Any other failure leaves one behind that nothing points to, so + * it is logged -- and not thrown, so that the caller goes on to the next document. + * + * @param uri the document to clear. + * @param open parameterized only so this can be unit-tested without an iceberg backend. + */ + def clearDocument( + uri: URI, + open: URI => VirtualDocument[_] = DocumentFactory.openDocument(_)._1 + ): Unit = + try open(uri).clear() + catch { + case _: DocumentNotFoundException => + case NonFatal(e) => logger.warn(s"Could not clear the document at $uri", e) + } + /** * Updates the size and row count stored for this port's result in operator_port_executions. * diff --git a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowResource.scala b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowResource.scala index 0918f3b4b2..dfa2abb1f0 100644 --- a/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowResource.scala +++ b/amber/src/main/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowResource.scala @@ -23,11 +23,7 @@ import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.scala.DefaultScalaModule import com.typesafe.scalalogging.LazyLogging import io.dropwizard.auth.Auth -import org.apache.texera.amber.core.storage.{ - DocumentFactory, - ExecutionResultUris, - WarehouseReadGuard -} +import org.apache.texera.amber.core.storage.{ExecutionResultUris, WarehouseReadGuard} import org.apache.texera.amber.core.virtualidentity.ExecutionIdentity import org.apache.texera.auth.SessionUser import org.apache.texera.auth.util.OwnerAccess @@ -674,17 +670,9 @@ class WorkflowResource extends LazyLogging { // Clean up document storage. While per-user warehouses are disabled, cleanup must // not reach into them (#6930) — those URIs are skipped. try { - uris.filterNot(WarehouseReadGuard.skipWhileDisabled(_)).foreach { uri => - try { - val (document, _) = DocumentFactory.openDocument(uri) - document.clear() - } catch { - case e: IllegalArgumentException if e.getMessage.contains("No storage is found") => - logger.warn(s"Storage for URI $uri not found, ignoring: ${e.getMessage}") - case NonFatal(e) => - logger.error(s"Failed to clear document for URI $uri", e) - } - } + uris + .filterNot(WarehouseReadGuard.skipWhileDisabled(_)) + .foreach(WorkflowExecutionsResource.clearDocument(_)) } catch { case NonFatal(e) => logger.error("Failed to clean up execution results", e) diff --git a/amber/src/main/scala/org/apache/texera/web/service/WorkflowService.scala b/amber/src/main/scala/org/apache/texera/web/service/WorkflowService.scala index 5d9b064af4..9419a991c7 100644 --- a/amber/src/main/scala/org/apache/texera/web/service/WorkflowService.scala +++ b/amber/src/main/scala/org/apache/texera/web/service/WorkflowService.scala @@ -26,6 +26,7 @@ import io.reactivex.rxjava3.disposables.{CompositeDisposable, Disposable} import io.reactivex.rxjava3.subjects.BehaviorSubject import org.apache.texera.amber.core.storage.{ DocumentFactory, + DocumentNotFoundException, ExecutionResultUris, WarehouseReadGuard } @@ -70,6 +71,7 @@ import java.net.URI import java.time.Instant import java.util.concurrent.ConcurrentHashMap import scala.jdk.CollectionConverters.IterableHasAsScala +import scala.util.control.NonFatal object WorkflowService { private val workflowServiceMapping = new ConcurrentHashMap[String, WorkflowService]() @@ -418,12 +420,7 @@ class WorkflowService( (resultUris ++ consoleMessagesUris).foreach { uri => if (WarehouseReadGuard.skipWhileDisabled(uri)) { logger.info(s"skipping cleanup of $uri: per-user warehouses are disabled") - } else - try DocumentFactory.openDocument(uri)._1.clear() - catch { - case error: Throwable => - logger.debug(s"Error processing document at $uri: ${error.getMessage}") - } + } else WorkflowExecutionsResource.clearDocument(uri) } // Expire any Iceberg snapshots for runtime statistics @@ -441,8 +438,8 @@ class WorkflowService( ) } } catch { - case error: Throwable => - logger.debug(s"Error processing document at $uri: ${error.getMessage}") + case _: DocumentNotFoundException => + case NonFatal(e) => logger.warn(s"Could not expire the snapshots of $uri", e) } } // Delete this execution's large binaries diff --git a/amber/src/test/python/core/storage/iceberg/test_iceberg_document.py b/amber/src/test/python/core/storage/iceberg/test_iceberg_document.py index 7c410876cc..4d9a5c383d 100644 --- a/amber/src/test/python/core/storage/iceberg/test_iceberg_document.py +++ b/amber/src/test/python/core/storage/iceberg/test_iceberg_document.py @@ -512,6 +512,18 @@ class TestIcebergDocumentWithMockCatalog: assert load_table_metadata.call_args.args == (document.catalog, "ns", "tbl") + def test_get_count_reports_an_unavailable_catalog_instead_of_zero(self, document): + document.catalog.load_table.side_effect = ConnectionError("catalog unavailable") + + with pytest.raises(ConnectionError, match="catalog unavailable"): + document.get_count() + + def test_reading_reports_an_unavailable_catalog_instead_of_no_rows(self, document): + document.catalog.load_table.side_effect = ConnectionError("catalog unavailable") + + with pytest.raises(ConnectionError, match="catalog unavailable"): + list(document.get()) + def test_a_negative_offset_is_rejected_rather_than_read_as_zero(self, document): """ IcebergIterator guards its file seek against having already skipped past diff --git a/amber/src/test/python/core/storage/iceberg/test_iceberg_utils_catalog.py b/amber/src/test/python/core/storage/iceberg/test_iceberg_utils_catalog.py index 4c180e751f..e9f37e7bb1 100644 --- a/amber/src/test/python/core/storage/iceberg/test_iceberg_utils_catalog.py +++ b/amber/src/test/python/core/storage/iceberg/test_iceberg_utils_catalog.py @@ -20,6 +20,7 @@ from unittest.mock import MagicMock, patch import pytest from fsspec.config import conf from fsspec.implementations.local import LocalFileSystem +from pyiceberg.exceptions import NoSuchNamespaceError, NoSuchTableError from pyiceberg.io.fsspec import FsspecFileIO from pyiceberg.partitioning import UNPARTITIONED_PARTITION_SPEC @@ -28,6 +29,7 @@ from core.storage.iceberg.iceberg_utils import ( create_postgres_catalog, create_rest_catalog, create_table, + load_table_metadata, ) @@ -390,3 +392,27 @@ class TestCreateTable: catalog.drop_table.assert_not_called() catalog.create_table.assert_called_once() + + +class TestLoadTableMetadata: + """ + Only a missing table is reported as None. Any other failure, such as an + unreachable catalog, has to reach the caller: taken for a missing table, it + would make a result that exists look gone, or a table read as empty. + """ + + @pytest.mark.parametrize("missing", [NoSuchTableError, NoSuchNamespaceError]) + def test_a_missing_table_or_namespace_is_none(self, missing): + catalog = MagicMock() + catalog.load_table.side_effect = missing("it does not exist") + + assert load_table_metadata(catalog, "ns", "tbl") is None + + catalog.load_table.assert_called_once_with("ns.tbl") + + def test_any_other_failure_reaches_the_caller(self): + catalog = MagicMock() + catalog.load_table.side_effect = ConnectionError("catalog unavailable") + + with pytest.raises(ConnectionError, match="catalog unavailable"): + load_table_metadata(catalog, "ns", "tbl") diff --git a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResourceSpec.scala b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResourceSpec.scala index 30e0acc185..50702f80ce 100644 --- a/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResourceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/resource/dashboard/user/workflow/WorkflowExecutionsResourceSpec.scala @@ -19,10 +19,19 @@ package org.apache.texera.web.resource.dashboard.user.workflow +import ch.qos.logback.classic.spi.ILoggingEvent +import ch.qos.logback.classic.{Level, Logger => LogbackLogger} +import ch.qos.logback.core.read.ListAppender import org.apache.pekko.actor.ActorSystem import org.apache.pekko.serialization.SerializationExtension import org.apache.pekko.testkit.TestKit -import org.apache.texera.amber.core.storage.{VFSURIFactory, WarehouseUnavailableException} +import org.apache.texera.amber.core.storage.model.VirtualDocument +import org.apache.texera.amber.core.storage.{ + DocumentNotFoundException, + VFSURIFactory, + WarehouseUnavailableException +} +import org.apache.texera.amber.core.tuple.Tuple import org.apache.texera.amber.core.virtualidentity.{ EmbeddedControlMessageIdentity, ExecutionIdentity, @@ -70,6 +79,7 @@ import org.apache.texera.web.service.ExecutionResultService import org.jose4j.jwt.JwtClaims import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.{BeforeAndAfterAll, BeforeAndAfterEach, PrivateMethodTester} +import org.slf4j.LoggerFactory import play.api.libs.json.Json import javax.ws.rs.{BadRequestException, ForbiddenException, WebApplicationException} @@ -83,6 +93,7 @@ import java.util.concurrent.TimeUnit import scala.collection.mutable.ArrayBuffer import scala.concurrent.duration.DurationInt import scala.concurrent.{Await, ExecutionContext, Future} +import scala.jdk.CollectionConverters._ class WorkflowExecutionsResourceSpec extends AnyFlatSpec @@ -644,6 +655,47 @@ class WorkflowExecutionsResourceSpec assert(survivorEids.contains(survivor.getEid)) } + // ─── clearDocument ──────────────────────────────────────────────────────── + + /** Clears a document whose `clear()` is `onClear`, and returns what was logged meanwhile. */ + private def clearing(onClear: => Unit): Seq[ILoggingEvent] = { + val uri = new URI("vfs:///clear-document-spec") + val document = new VirtualDocument[Tuple] { + override def getURI: URI = uri + override def clear(): Unit = onClear + } + val logger = LoggerFactory + .getLogger(classOf[WorkflowExecutionsResource]) + .asInstanceOf[LogbackLogger] + val appender = new ListAppender[ILoggingEvent] + val previousLevel = logger.getLevel + appender.start() + logger.addAppender(appender) + logger.setLevel(Level.WARN) + try WorkflowExecutionsResource.clearDocument(uri, _ => document) + finally { + logger.setLevel(previousLevel) + logger.detachAppender(appender) + } + appender.list.asScala.toSeq + } + + "clearDocument" should "clear the document it opens" in { + var cleared = false + assert(clearing { cleared = true }.isEmpty) + assert(cleared) + } + + it should "pass over a document that is already gone" in { + assert(clearing(throw new DocumentNotFoundException("gone")).isEmpty) + } + + it should "log any other failure rather than throw it" in { + val logged = clearing(throw new RuntimeException("catalog unavailable")) + assert(logged.map(_.getLevel) == Seq(Level.WARN)) + assert(logged.head.getThrowableProxy.getMessage == "catalog unavailable") + } + private def grantAccess(uid: Integer, privilege: PrivilegeEnum): Unit = { val access = new WorkflowUserAccess access.setUid(uid) diff --git a/amber/src/test/scala/org/apache/texera/web/service/WorkflowServiceSpec.scala b/amber/src/test/scala/org/apache/texera/web/service/WorkflowServiceSpec.scala index c26dd76d0b..a098d1d3b5 100644 --- a/amber/src/test/scala/org/apache/texera/web/service/WorkflowServiceSpec.scala +++ b/amber/src/test/scala/org/apache/texera/web/service/WorkflowServiceSpec.scala @@ -20,8 +20,13 @@ package org.apache.texera.web.service import io.reactivex.rxjava3.disposables.Disposable +import org.apache.texera.amber.core.storage.VFSURIFactory import org.apache.texera.amber.core.storage.result.{OperatorResultMetadata, WorkflowResultStore} -import org.apache.texera.amber.core.virtualidentity.{OperatorIdentity, WorkflowIdentity} +import org.apache.texera.amber.core.virtualidentity.{ + ExecutionIdentity, + OperatorIdentity, + WorkflowIdentity +} import org.apache.texera.amber.core.workflow.{WorkflowContext, WorkflowSettings} import org.apache.texera.amber.engine.architecture.rpc.controlreturns.WorkflowAggregatedState import org.apache.texera.amber.engine.architecture.rpc.controlreturns.WorkflowAggregatedState.{ @@ -62,6 +67,7 @@ import org.apache.texera.web.model.websocket.event.{ WorkflowStateEvent } import org.apache.texera.web.model.websocket.request.WorkflowExecuteRequest +import org.apache.texera.web.resource.dashboard.user.workflow.WorkflowExecutionsResource import org.apache.texera.web.storage.{ExecutionStateStore, WorkflowStateStore} import org.scalatest.BeforeAndAfterAll import org.scalatest.flatspec.AnyFlatSpec @@ -118,12 +124,11 @@ import scala.collection.mutable.ArrayBuffer * `SERIAL`: a fresh `MockTexeraDB` database hands out eid 1, and `objects/1/` is the prefix * `LargeBinaryManager` shares with its DEFAULT_EXECUTION_ID sentinel — a developer with * `bin/local-dev.sh up` running would have that prefix recursively deleted for real. - * - the runtime-statistics block. Its URI column is NULL in every fixture, so the loop body - * runs zero times; a non-NULL value there would abort the whole method (see below) before - * the execution insert this suite also pins. + * - the runtime-statistics block, except that a failure in it does not stop the run: + * `previousEid` names a document that is not there, so no snapshot is ever expired. * - which arm of `WarehouseReadGuard.skipWhileDisabled` either loop takes: both arms end in - * `DocumentFactory`, which needs a live Iceberg/LakeFS backend, and the loop body swallows - * every `Throwable`. + * `DocumentFactory`, which needs a live Iceberg/LakeFS backend, and no failure there leaves + * the loop body. * - swapping the two URI reads with each other. That is an equivalent mutant, not a gap: the * two lists are concatenated and every element is treated identically. * @@ -261,7 +266,7 @@ class WorkflowServiceSpec */ private val otherWorkflowEid = 941103 - /** The read-before-delete case's execution; the only fixture with a non-NULL URI column. */ + /** The read-before-delete case's execution; the only fixture with a registry URI. */ private val probeEid = 941104 private val fixtureEids: Seq[Integer] = @@ -320,6 +325,14 @@ class WorkflowServiceSpec insertExecution(otherUnitEid, testWid, otherCuid, "other-unit-run") insertExecution(otherWorkflowEid, otherWid, testCuid, "other-workflow-run") insertExecution(probeEid, testWid, probeCuid, "probe-run") + WorkflowExecutionsResource.updateRuntimeStatsUri( + testWid, + previousEid, + VFSURIFactory.createRuntimeStatisticsURI( + WorkflowIdentity(testWid), + ExecutionIdentity(previousEid) + ) + ) // Keep the SERIAL sequence ahead of our explicit fixture ids, so the execution that // production inserts below cannot land on eid 1 -- LargeBinaryManager's DEFAULT_EXECUTION_ID @@ -354,7 +367,7 @@ class WorkflowServiceSpec registerPort(otherWorkflowEid, s"other-wf-port-$i") } registerOperator(probeEid, "probe-op") - // The one non-NULL URI in the fixture: syntactically a URI, but not a `vfs` one, so + // The one registry URI in the fixture: syntactically a URI, but not a `vfs` one, so // `VFSURIFactory.decodeURI` rejects it. See the header -- this is the witness that the // registry was read, not an assertion that malformed rows ought to be fatal. registerPort(probeEid, "probe-port", resultUri = "bogus:///stranded") diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/DocumentFactory.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/DocumentFactory.scala index 4915d57897..78e7acb8d7 100644 --- a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/DocumentFactory.scala +++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/DocumentFactory.scala @@ -36,6 +36,13 @@ import org.apache.iceberg.{Schema => IcebergSchema} import java.net.URI +/** + * Signals that a URI addresses a document with no storage behind it, as one whose table was + * deleted. A distinct type so callers can tell it from a document that could not be opened. It + * is an `IllegalArgumentException` because `openDocument` has always thrown one here. + */ +class DocumentNotFoundException(message: String) extends IllegalArgumentException(message) + object DocumentFactory { val ICEBERG = "iceberg" @@ -196,7 +203,7 @@ object DocumentFactory { storageKey ) .getOrElse( - throw new IllegalArgumentException("No storage is found for the given URI") + throw new DocumentNotFoundException("No storage is found for the given URI") ) val amberSchema = IcebergUtil.fromIcebergSchema(table.schema()) diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/result/iceberg/IcebergDocument.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/result/iceberg/IcebergDocument.scala index 26cebcac96..0afc2e114a 100644 --- a/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/result/iceberg/IcebergDocument.scala +++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/core/storage/result/iceberg/IcebergDocument.scala @@ -19,6 +19,7 @@ package org.apache.texera.amber.core.storage.result.iceberg +import com.typesafe.scalalogging.LazyLogging import org.apache.texera.amber.core.storage.IcebergCatalogInstance import org.apache.texera.amber.core.storage.model.{BufferedItemWriter, VirtualDocument} import org.apache.texera.amber.core.storage.util.StorageUtil.{withLock, withReadLock, withWriteLock} @@ -40,6 +41,7 @@ import java.util.zip.{ZipEntry, ZipOutputStream} import scala.collection.mutable import scala.jdk.CollectionConverters._ import scala.util.Using +import scala.util.control.NonFatal object Constants { // Default buffer size for streaming Parquet files to outside @@ -68,7 +70,8 @@ private[storage] class IcebergDocument[T >: Null <: AnyRef]( val deserde: (org.apache.iceberg.Schema, Record) => T, val warehouse: Option[String] = None ) extends VirtualDocument[T] - with OnIceberg { + with OnIceberg + with LazyLogging { private val lock = new ReentrantReadWriteLock() @@ -264,7 +267,21 @@ private[storage] class IcebergDocument[T >: Null <: AnyRef]( // bound to a catalog the bounded cache may have closed, and re-resolving // also keeps this warehouse's cache entry live for as long as the reader // polls. Snapshot continuity lives in lastSnapshotId, not in the Table. - table = loadTableMetadata() + // + // Once resolved, a later seek only looks for rows committed since, after every row + // seen so far has been returned. Failing it must not fail the read, so the table + // resolved last stands in: it has nothing newer. A first resolve still throws, since + // a table that was never resolved must not read as empty. + table = + try loadTableMetadata() + catch { + case NonFatal(e) if table.isDefined => + logger.warn( + s"Could not look for newer rows of $tableNamespace.$tableName", + e + ) + table + } // Retrieve and sort the file scan tasks by file sequence number. // Materialize inside `Using.resource` so the `planFiles()` diff --git a/common/workflow-core/src/main/scala/org/apache/texera/amber/util/IcebergUtil.scala b/common/workflow-core/src/main/scala/org/apache/texera/amber/util/IcebergUtil.scala index 7c0dcb52f9..4a9d208ada 100644 --- a/common/workflow-core/src/main/scala/org/apache/texera/amber/util/IcebergUtil.scala +++ b/common/workflow-core/src/main/scala/org/apache/texera/amber/util/IcebergUtil.scala @@ -43,7 +43,11 @@ import org.apache.iceberg.{ Schema => IcebergSchema } import org.apache.iceberg.catalog.Namespace -import org.apache.iceberg.exceptions.AlreadyExistsException +import org.apache.iceberg.exceptions.{ + AlreadyExistsException, + NoSuchNamespaceException, + NoSuchTableException +} import java.nio.ByteBuffer import java.nio.file.Path @@ -230,7 +234,10 @@ object IcebergUtil { /** * Loads metadata for an existing Iceberg table. * - Returns `Some(Table)` if the table exists and is successfully loaded. - * - Returns `None` if the table does not exist or cannot be loaded. + * - Returns `None` if the table, or its namespace, does not exist. + * + * Any other failure is thrown, such as a catalog that cannot be reached. Taken for a missing + * table, it would make a result that exists look deleted, or a table read as empty. * * @param catalog the Iceberg catalog to load the table from. * @param tableNamespace the namespace of the table. @@ -246,7 +253,7 @@ object IcebergUtil { try { Some(catalog.loadTable(identifier)) } catch { - case _: Exception => None + case _: NoSuchTableException | _: NoSuchNamespaceException => None } } diff --git a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/DocumentFactorySpec.scala b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/DocumentFactorySpec.scala index f219383f25..3bb92b0dc0 100644 --- a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/DocumentFactorySpec.scala +++ b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/DocumentFactorySpec.scala @@ -317,10 +317,12 @@ class DocumentFactorySpec extends AnyFlatSpec with Matchers with BeforeAndAfterA schemaOpt.get.getAttributes.map(_.getName) should contain("v") } - it should "throw IllegalArgumentException when opening a vfs URI with no backing storage" in { - val thrown = intercept[IllegalArgumentException] { + it should "throw DocumentNotFoundException when opening a vfs URI with no backing storage" in { + val thrown = intercept[DocumentNotFoundException] { DocumentFactory.openDocument(freshResultURI()) } thrown.getMessage should include("No storage is found") + // Callers that catch the type it has always been still match. + thrown shouldBe an[IllegalArgumentException] } } diff --git a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/result/iceberg/FailingCatalog.scala b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/result/iceberg/FailingCatalog.scala new file mode 100644 index 0000000000..92a602e395 --- /dev/null +++ b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/result/iceberg/FailingCatalog.scala @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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. + */ + +package org.apache.texera.amber.core.storage.result.iceberg + +import org.apache.iceberg.Table +import org.apache.iceberg.catalog.{Catalog, TableIdentifier} + +/** + * Test helper: lets the first `succeeding` `loadTable` calls through and fails the rest, as an + * unreachable catalog would. A missing table is not a failure: `delegate` still reports it. + */ +class FailingCatalog(delegate: Catalog, succeeding: Int) extends CountingCatalog(delegate) { + override def loadTable(identifier: TableIdentifier): Table = { + if (loadTableCalls.get() >= succeeding) { + throw new RuntimeException("catalog unavailable") + } + super.loadTable(identifier) + } +} diff --git a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/result/iceberg/IcebergDocumentSpec.scala b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/result/iceberg/IcebergDocumentSpec.scala index 469c7f94db..1418ab763e 100644 --- a/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/result/iceberg/IcebergDocumentSpec.scala +++ b/common/workflow-core/src/test/scala/org/apache/texera/amber/core/storage/result/iceberg/IcebergDocumentSpec.scala @@ -24,7 +24,7 @@ import org.apache.texera.amber.core.storage.LocalHadoopIcebergCatalog import org.apache.texera.amber.core.storage.model.VirtualDocument import org.apache.texera.amber.core.tuple.{AttributeType, Schema, Tuple} import org.apache.texera.amber.util.IcebergUtil -import org.apache.iceberg.catalog.TableIdentifier +import org.apache.iceberg.catalog.{Catalog, TableIdentifier} import org.apache.iceberg.data.Record import org.apache.iceberg.exceptions.NoSuchTableException import org.apache.iceberg.io.CloseableIterator @@ -427,37 +427,56 @@ class IcebergDocumentSpec extends AnyFlatSpec with Matchers with BeforeAndAfterA doc.asInstanceOf[IcebergDocument[Tuple]].tableNamespace shouldBe tableNamespace doc.asInstanceOf[IcebergDocument[Tuple]].tableName shouldBe name } + + /** + * A document of `tableName` that reads through `through`. It overrides its catalog rather than + * replacing a shared one: outside `rest`, every warehouse shares one entry. + */ + private def documentThrough(through: Catalog, tableName: String): IcebergDocument[Tuple] = + new IcebergDocument[Tuple](tableNamespace, tableName, icebergSchema, serde, deserde) { + override def catalog: Catalog = through + } + + /** + * Writes `rows` rows, and returns a document that reads them through a catalog which lets + * `succeeding` `loadTable` calls through before it fails. + */ + private def documentOnFailingCatalog(rows: Int, succeeding: Int): IcebergDocument[Tuple] = { + val tableName = freshTableName() + write(newDocument(tableName), (0 until rows).map(tuple)) + documentThrough(new FailingCatalog(IcebergCatalogInstance.getInstance(), succeeding), tableName) + } + + it should "throw rather than count 0 rows when its catalog is unavailable" in { + val error = intercept[RuntimeException](documentOnFailingCatalog(3, 0).getCount) + error.getMessage shouldBe "catalog unavailable" + } + + it should "throw rather than read as empty when its catalog is unavailable" in { + val error = intercept[RuntimeException](documentOnFailingCatalog(3, 0).get().toList) + error.getMessage shouldBe "catalog unavailable" + } + + it should "keep the rows it has read when its catalog fails while it looks for newer ones" in { + // The first call resolves the table; the second is the look for files committed since, made + // once every row of that snapshot has been returned. + documentOnFailingCatalog(3, 1).get().toList should have size 3 + } + it should "re-resolve its catalog on every seek, keeping a polling reader's entry live" in { // #7290 review: a reader that refreshed a pinned Table never touched the catalog // cache again, so a long poll looked idle -- expiry could close the catalog under // it. Per-seek re-resolution touches the cache at iterator construction AND every // seek; the pinned-refresh implementation stopped at the construction touch. val tableName = freshTableName() - IcebergUtil.createTable( - IcebergCatalogInstance.getInstance(), - tableNamespace, - tableName, - icebergSchema, - overrideIfExists = true - ) + write(newDocument(tableName), (1 to 3).map(tuple)) val counting = new CountingCatalog(IcebergCatalogInstance.getInstance()) - IcebergCatalogInstance.replaceInstance(counting, Some("iceberg-doc-spec-counting")) - val doc = new IcebergDocument[Tuple]( - tableNamespace, - tableName, - icebergSchema, - serde, - deserde, - Some("iceberg-doc-spec-counting") - ) - write(doc, (1 to 3).map(tuple)) - val before = counting.loadTableCalls.get() - doc.get().toList should have size 3 + documentThrough(counting, tableName).get().toList should have size 3 // Exactly the construction-time seek and the final exhausted-files seek resolve // through the catalog: the pinned-refresh implementation touched it only once, // and an eager constructor-time load would add a wasted third round trip. - (counting.loadTableCalls.get() - before) shouldBe 2 + counting.loadTableCalls.get() shouldBe 2 } } diff --git a/common/workflow-core/src/test/scala/org/apache/texera/amber/util/IcebergUtilSpec.scala b/common/workflow-core/src/test/scala/org/apache/texera/amber/util/IcebergUtilSpec.scala index 04ffad376a..bc3c2c03d5 100644 --- a/common/workflow-core/src/test/scala/org/apache/texera/amber/util/IcebergUtilSpec.scala +++ b/common/workflow-core/src/test/scala/org/apache/texera/amber/util/IcebergUtilSpec.scala @@ -24,7 +24,12 @@ import org.apache.texera.amber.util.IcebergUtil.toIcebergSchema import org.apache.hadoop.fs.FileSystem import org.apache.iceberg.catalog.{Catalog, TableIdentifier} import org.apache.iceberg.data.GenericRecord -import org.apache.iceberg.exceptions.{AlreadyExistsException, RESTException} +import org.apache.iceberg.exceptions.{ + AlreadyExistsException, + NoSuchNamespaceException, + NoSuchTableException, + RESTException +} import org.apache.iceberg.types.Types import org.apache.iceberg.{Schema => IcebergSchema} import org.scalamock.scalatest.MockFactory @@ -457,14 +462,28 @@ class IcebergUtilSpec extends AnyFlatSpec with MockFactory { ) } - it should "return None when loading table metadata fails" in { + it should "return None when the table or its namespace does not exist" in { + val identifier = TableIdentifier.of("test_namespace", "test_table") + Seq(new NoSuchTableException("no table"), new NoSuchNamespaceException("no namespace")) + .foreach { missing => + val catalog = mock[Catalog] + (catalog.loadTable _).expects(identifier).throwing(missing) + + assert(IcebergUtil.loadTableMetadata(catalog, "test_namespace", "test_table").isEmpty) + } + } + + it should "throw rather than return None when loading table metadata fails" in { val catalog = mock[Catalog] val identifier = TableIdentifier.of("test_namespace", "test_table") (catalog.loadTable _) .expects(identifier) .throwing(new RuntimeException("catalog unavailable")) - assert(IcebergUtil.loadTableMetadata(catalog, "test_namespace", "test_table").isEmpty) + val error = intercept[RuntimeException] { + IcebergUtil.loadTableMetadata(catalog, "test_namespace", "test_table") + } + assert(error.getMessage == "catalog unavailable") } it should "surface RESTException when createRestCatalog cannot reach the REST endpoint" in { diff --git a/result-service/src/main/scala/org/apache/texera/service/resource/ResultResource.scala b/result-service/src/main/scala/org/apache/texera/service/resource/ResultResource.scala index ca65d59dfb..ded8891e69 100644 --- a/result-service/src/main/scala/org/apache/texera/service/resource/ResultResource.scala +++ b/result-service/src/main/scala/org/apache/texera/service/resource/ResultResource.scala @@ -38,6 +38,7 @@ import jakarta.ws.rs.{ import org.apache.texera.amber.core.storage.model.VirtualDocument import org.apache.texera.amber.core.storage.{ DocumentFactory, + DocumentNotFoundException, WarehouseReadGuard, WarehouseUnavailableException } @@ -265,7 +266,7 @@ class ResultResource { (document._1.asInstanceOf[VirtualDocument[Tuple]], document._2.get) } catch { case e: WarehouseUnavailableException => throw new ServiceUnavailableException(e.getMessage) - case e: IllegalArgumentException if e.getMessage.contains("No storage is found") => + case _: DocumentNotFoundException => throw new NotFoundException(s"the result of operator $operatorId is no longer stored") } } diff --git a/result-service/src/test/scala/org/apache/texera/service/resource/ResultResourceSpec.scala b/result-service/src/test/scala/org/apache/texera/service/resource/ResultResourceSpec.scala index b1f2f75151..9810f4d92f 100644 --- a/result-service/src/test/scala/org/apache/texera/service/resource/ResultResourceSpec.scala +++ b/result-service/src/test/scala/org/apache/texera/service/resource/ResultResourceSpec.scala @@ -29,11 +29,12 @@ import org.apache.iceberg.catalog.TableIdentifier import org.apache.iceberg.types.Types import org.apache.texera.amber.core.storage.{ DocumentFactory, + IcebergCatalogInstance, LocalHadoopIcebergCatalog, VFSURIFactory } import org.apache.texera.amber.core.storage.model.{BufferedItemWriter, VirtualDocument} -import org.apache.texera.amber.core.storage.result.iceberg.OnIceberg +import org.apache.texera.amber.core.storage.result.iceberg.{FailingCatalog, OnIceberg} import org.apache.texera.amber.core.tuple.{Attribute, AttributeType, Schema, Tuple} import org.apache.texera.amber.core.virtualidentity.{ ExecutionIdentity, @@ -204,6 +205,14 @@ class ResultResourceSpec getDSLContext.deleteFrom(WORKFLOW_EXECUTIONS).execute() } + /** Runs `body` on a catalog that lets `succeeding` `loadTable` calls through, then fails. */ + private def withFailingCatalog(succeeding: Int)(body: => Unit): Unit = { + val catalog = IcebergCatalogInstance.getInstance() + IcebergCatalogInstance.replaceInstance(new FailingCatalog(catalog, succeeding)) + try body + finally IcebergCatalogInstance.replaceInstance(catalog) + } + /** An execution of the workflow, on the owner's computing unit unless `on` says otherwise. */ private def insertExecution( startedBy: User, @@ -608,6 +617,24 @@ class ResultResourceSpec get(owner, pagesPath(eid)).getStatus shouldBe 500 } + it should "answer 500, not 404, when the catalog is unavailable" in { + val eid = insertExecution(owner) + storeResult(eid) + + withFailingCatalog(succeeding = 0) { + get(owner, pagesPath(eid)).getStatus shouldBe 500 + } + } + + it should "answer 500, not an empty page, when the catalog fails after opening the result" in { + val eid = insertExecution(owner) + storeResult(eid) + + withFailingCatalog(succeeding = 1) { + get(owner, pagesPath(eid)).getStatus shouldBe 500 + } + } + it should "answer 503 for a result in a warehouse it cannot read" in { val eid = insertExecution(owner) val port = globalPort("op")
