diff --git a/core/src/main/scala/app/softnetwork/elastic/client/SearchApi.scala b/core/src/main/scala/app/softnetwork/elastic/client/SearchApi.scala index a6e5de93..3918176d 100644 --- a/core/src/main/scala/app/softnetwork/elastic/client/SearchApi.scala +++ b/core/src/main/scala/app/softnetwork/elastic/client/SearchApi.scala @@ -113,14 +113,16 @@ trait SearchApi extends ElasticConversion with ElasticClientHelpers with SchemaC * SCHEMA-17 (A-163) -- where no schema is found, the answer is decided here, in the mode of the * call: a source of `*` parts only that matches no index is typed as an EMPTY table in both * modes (`run` answers 0 rows); in `describe`'s mode (`executeSubqueries = false`) an unknown - * concrete source, or a remembered miss, is its 404 and any other lookup failure keeps its - * status (`operation = "describe"`); `run` sends the statement verbatim. + * concrete source is its 404 and any other lookup failure keeps its status (`operation = + * "describe"`); `run` sends the statement verbatim. * * The cache keeps successes only, so a source it cannot resolve -- an unknown index without a * template -- would otherwise cost one failed lookup (two round trips + WARN lines) per - * statement. [[schemaMisses]] remembers a 404 miss for [[schemaMissTtlMs]] and skips the lookup; - * the literal is verbatim either way. A NON-404 failure (a transient 5xx, a thrown lookup) is - * never remembered, so a cluster blip cannot disable the resolution for the TTL. + * statement. [[schemaMisses]] remembers a 404 miss for [[schemaMissTtlMs]] and `run` skips the + * lookup while it stands; the literal is verbatim either way. `describe` reads the source again + * (R-169, [[lookupSchema]]): another client may have created it since. A NON-404 failure (a + * transient 5xx, a thrown lookup) is never remembered, so a cluster blip cannot disable the + * resolution for the TTL. * * `private[client]`: `IndicesApi` reuses it for the DELETE / UPDATE by-query search bodies. * @@ -325,14 +327,18 @@ trait SearchApi extends ElasticConversion with ElasticClientHelpers with SchemaC ) ) else unresolved(phaseOne, Some(source)) - lookupSchema(sources) match { + // R-169 -- the lookup in the mode of the call ([[lookupSchema]]): `describe` reads a + // remembered miss again, `run` skips it + val describing = !executeSubqueries + lookupSchema(sources, describing) match { case Some(lookup) => + // `run` records what it read here; `describe`'s lookup recorded itself + if (!describing) recordLookup(source, lookup) lookup match { case Success(ElasticSuccess(cached)) => - schemaMisses.remove(source) // SCHEMA-2 (D10) -- an explicitly selected path the cached mapping lacks reloads it // ONCE per TTL (memoized), so a field mapped since is read by its type - val schema = reloadedFor(phaseOne, sources, cached) + val schema = reloadedFor(phaseOne, sources, cached, describing) // SCHEMA-17 (A-191) -- this statement over this very schema: answered from memory answers match { case Some(memo) if !single.hasWhereSubqueries => @@ -344,7 +350,6 @@ trait SearchApi extends ElasticConversion with ElasticClientHelpers with SchemaC } attach(schema) case Success(ElasticFailure(error)) => - if (error.statusCode.contains(404)) rememberSchemaMiss(source) logger.debug( s"Schema of '$source' unavailable (${error.message}) - temporal literals forwarded verbatim" ) @@ -362,7 +367,7 @@ trait SearchApi extends ElasticConversion with ElasticClientHelpers with SchemaC ) ) } - // a remembered miss: the 404 it remembers + // `run`'s remembered miss: the 404 it remembers (`describe` never skips its lookup) case None if schemaMissed(source) => noSchema(ElasticError.notFound(index = source, operation = "describe")) case None => unresolved(phaseOne, Some(source)) @@ -454,15 +459,25 @@ trait SearchApi extends ElasticConversion with ElasticClientHelpers with SchemaC }.distinct /** [[reloadedFor]] over the paths `statement` selects explicitly. */ - private def reloadedFor(statement: SingleSearch, sources: Seq[String], schema: Schema): Schema = - reloadedFor(explicitPaths(statement), sources, schema) + private def reloadedFor( + statement: SingleSearch, + sources: Seq[String], + schema: Schema, + describing: Boolean + ): Schema = + reloadedFor(explicitPaths(statement), sources, schema, describing) /** `schema`, or -- when `paths` holds a path it lacks on ONE concrete source, not reloaded for * that path within the source's TTL -- the source's mapping read again - * (`IndicesApi.invalidateSchema`, then [[lookupSchema]]); `schema` when the reload fails. - * `paths` is by name: read only for a concrete source. - */ - private def reloadedFor(paths: => Seq[String], sources: Seq[String], schema: Schema): Schema = + * (`IndicesApi.invalidateSchema`, then [[lookupSchema]] in the caller's mode); `schema` when the + * reload fails. `paths` is by name: read only for a concrete source. + */ + private def reloadedFor( + paths: => Seq[String], + sources: Seq[String], + schema: Schema, + describing: Boolean + ): Schema = this match { case indices: IndicesApi if sources.size == 1 && !sources.head.contains("*") && !sources.head.contains(",") => @@ -482,7 +497,7 @@ trait SearchApi extends ElasticConversion with ElasticClientHelpers with SchemaC s"Mapping of '$source' reloaded for ${fresh.mkString(", ")}, absent from its cached schema" ) indices.invalidateSchema(source) - lookupSchema(sources) match { + lookupSchema(sources, describing) match { case Some(Success(ElasticSuccess(reloaded))) => reloaded case _ => schema } @@ -498,19 +513,52 @@ trait SearchApi extends ElasticConversion with ElasticClientHelpers with SchemaC * remembered by -- the sources joined with commas; a user who may not read a mapping is typed * from `_field_caps` ([[IndicesApi.loadQuerySchema]], SCHEMA-7 D7). * - * `None` when no lookup is made: a client that is not an [[IndicesApi]], or a remembered miss. - */ - private def lookupSchema(sources: Seq[String]): Option[Try[ElasticResult[Schema]]] = { + * R-169 -- and THE rule every reader of a remembered miss ([[schemaMisses]]) applies, in the + * mode of its call (#292): + * - `run` (`describing = false`: the attach of an executing statement, a subquery's scope + * check and its inner column's type while it executes): a remembered miss skips the lookup, + * so the statement runs untyped while it stands; the caller records what it reads, as + * before; + * - `describe` (`describing = true`: `describe`'s attach, its pre-execution scope check, + * [[resolvePerTable]] 's legs, [[attachDerived]] 's sources): the source is read AGAIN, + * since another client may have created it since (an ingest that auto-creates it, a raw + * `PUT`), and the outcome is recorded here ([[recordLookup]]): found, the miss is forgotten, + * so the next `run` is typed; a 404, it is remembered afresh. `describe` answers what `run` + * answers once it reads the mapping. + * + * Cost: no negative caching on `describe`'s path -- a source that is still absent is looked up + * on every describe that reads it (an error path); `run`'s negative cache is unchanged. + * + * `None` when no lookup is made: a client that is not an [[IndicesApi]], or a remembered miss in + * `run`'s mode. + */ + private def lookupSchema( + sources: Seq[String], + describing: Boolean + ): Option[Try[ElasticResult[Schema]]] = { val source = sources.mkString(",") this match { // SCHEMA-7 (D7): ONE seam for both origins -- the mapping, or `_field_caps` where the mapping // is refused (`IndicesApi.loadQuerySchema`) - case indices: IndicesApi if !schemaMissed(source) => - Some(Try(indices.loadQuerySchema(source))) + case indices: IndicesApi if describing || !schemaMissed(source) => + val lookup = Try(indices.loadQuerySchema(source)) + if (describing) recordLookup(source, lookup) + Some(lookup) case _ => None } } + /** What a lookup of `source` -- [[lookupSchema]] 's key -- tells [[schemaMisses]]: found, the + * miss is forgotten; a 404, it is remembered from now; any other failure is never remembered. + */ + private def recordLookup(source: String, lookup: Try[ElasticResult[Schema]]): Unit = + lookup match { + case Success(ElasticSuccess(_)) => forgetSchemaMiss(source) + case Success(ElasticFailure(error)) if error.statusCode.contains(404) => + rememberSchemaMiss(source) + case _ => + } + /** SCHEMA-6 (D11) -- `single` with each derived table and CTE reference typed from its body * (`DerivedTable.attach`), every index source by [[lookupSchema]] (cached: one read per index * per TTL): the typing API of the relational engine, which types the statements core refuses to @@ -536,9 +584,11 @@ trait SearchApi extends ElasticConversion with ElasticClientHelpers with SchemaC } .map(branches => multiple.copy(requests = branches)) - /** The schema of an index source for [[attachDerived]]: [[lookupSchema]]'s, `None` on a miss. */ + /** The schema of an index source for [[attachDerived]], a typing API that runs nothing: + * [[lookupSchema]] 's in `describe`'s mode (R-169), `None` when unknown. + */ private def derivedLookup(sources: Seq[String]): Option[Schema] = - lookupSchema(sources) match { + lookupSchema(sources, describing = true) match { case Some(Success(ElasticSuccess(schema))) => Some(schema) case _ => None } @@ -598,18 +648,14 @@ trait SearchApi extends ElasticConversion with ElasticClientHelpers with SchemaC } } - /** One leg of [[resolvePerTable]]: [[lookupSchema]] 's schema (a 404 remembered as the attach of - * [[resolveWithSchema]] remembers it), reloaded for the `paths` it lacks ([[reloadedFor]]); - * `None` when unknown. + /** One leg of [[resolvePerTable]]: [[lookupSchema]] 's schema in `describe`'s mode (a remembered + * miss read again, the outcome recorded there, R-169), reloaded for the `paths` it lacks + * ([[reloadedFor]]); `None` when unknown. */ private def legSchema(leg: String, paths: => Seq[String]): Option[Schema] = - lookupSchema(Seq(leg)) match { + lookupSchema(Seq(leg), describing = true) match { case Some(Success(ElasticSuccess(cached))) => - schemaMisses.remove(leg) - Some(reloadedFor(paths, Seq(leg), cached)) - case Some(Success(ElasticFailure(error))) => - if (error.statusCode.contains(404)) rememberSchemaMiss(leg) - None + Some(reloadedFor(paths, Seq(leg), cached, describing = true)) case _ => None } @@ -622,10 +668,11 @@ trait SearchApi extends ElasticConversion with ElasticClientHelpers with SchemaC * nothing). The caller (`SubqueryResolver`) reads it for ONE decision: a `text` column cannot * carry a terms aggregation, so mode P is declined for it. An unknown mapping therefore keeps * the cheap default, and an Elasticsearch refusal propagates loudly with the inner statement's - * own message. + * own message. Read by `run` alone -- mode P is chosen only for a subquery that executes -- so + * in `run`'s mode ([[lookupSchema]]). */ private[client] def innerColumnType(inner: SingleSearch, name: String): Option[SQLType] = - resolvedSchema(inner).flatMap(_.find(name).map(_.dataType)) + resolvedSchema(inner, describing = false).flatMap(_.find(name).map(_.dataType)) /** Story 22.3 (AD-3) — the SCHEMA-aware SCOPE check, generalised from story 22.2's * `bareNameCorrelation`. Reached only for a statement the closure guard did NOT already route to @@ -650,21 +697,34 @@ trait SearchApi extends ElasticConversion with ElasticClientHelpers with SchemaC outer: SingleSearch, inner: SingleSearch ): Option[String] = - bareNameCorrelation(outer, inner).orElse(unresolvedQualifier(outer, inner)) + scopeCorrelation(outer, inner, describing = false) + + /** [[scopeCorrelation]] in the mode of the call (R-169, [[lookupSchema]]): `describing` -- + * `GatewayApi.describe`'s pre-execution checks (`SubqueryResolver.resolve(_, _, executes = + * false)`) -- reads a remembered miss again, as describe's attach does; `run` skips it. + */ + private[client] def scopeCorrelation( + outer: SingleSearch, + inner: SingleSearch, + describing: Boolean + ): Option[String] = + bareNameCorrelation(outer, inner, describing) + .orElse(unresolvedQualifier(outer, inner, describing)) /** Question 2 of [[scopeCorrelation]]. `Schema.find(head)` answers for an OBJECT field too (it * returns the object column itself), so one lookup separates `address.city` from a typo. */ private def unresolvedQualifier( outer: SingleSearch, - inner: SingleSearch + inner: SingleSearch, + describing: Boolean ): Option[String] = // 🔴 An EMPTY mapping is a mapping GAP, never evidence that a name does not exist: an index // created but not yet written to, or one whose dynamic mapping has not caught up, would // otherwise turn every dotted object path in a subquery body into a 400. Same posture as the // schema-absent conditions in `resolvedSchema` — a mapping we do not have must never become a // rejection. - resolvedSchema(inner).filter(_.columns.nonEmpty).flatMap { innerMapping => + resolvedSchema(inner, describing).filter(_.columns.nonEmpty).flatMap { innerMapping => val chain = SubqueryScope.chain(inner, Seq(outer)) inner.referencedIdentifiers.iterator .filter(id => @@ -698,11 +758,12 @@ trait SearchApi extends ElasticConversion with ElasticClientHelpers with SchemaC private def bareNameCorrelation( outer: SingleSearch, - inner: SingleSearch + inner: SingleSearch, + describing: Boolean ): Option[String] = for { - innerMapping <- resolvedSchema(inner) - outerMapping <- resolvedSchema(outer) + innerMapping <- resolvedSchema(inner, describing) + outerMapping <- resolvedSchema(outer, describing) // 🔴 A name the INNER SELECT list defines as an alias is an inner name, whatever the mappings // say: `IN (SELECT id AS cid FROM customers ORDER BY cid)` references `cid`, which no mapping // carries — and rejecting it because the OUTER index happens to have a `cid` column would @@ -721,14 +782,14 @@ trait SearchApi extends ElasticConversion with ElasticClientHelpers with SchemaC outerMapping.name ) - /** The schema of a statement's sources, when it can be read: [[lookupSchema]], the one the attach - * reads -- an index pattern or a list of sources included (their merged schema), so a subquery - * over `logs-*` is scoped as one over a single index is. + /** The schema of a statement's sources, when it can be read: [[lookupSchema]] in the caller's + * mode, the one the attach reads -- an index pattern or a list of sources included (their merged + * schema), so a subquery over `logs-*` is scoped as one over a single index is. */ - private def resolvedSchema(s: SingleSearch): Option[Schema] = + private def resolvedSchema(s: SingleSearch, describing: Boolean): Option[Schema] = s.sources.distinct match { case sources if sources.nonEmpty => - lookupSchema(sources).flatMap { + lookupSchema(sources, describing).flatMap { case Success(ElasticSuccess(schema)) => Some(schema) case _ => None } @@ -758,13 +819,16 @@ trait SearchApi extends ElasticConversion with ElasticClientHelpers with SchemaC * does not exist cannot ask to be forgotten sooner. * * 🔴 And deliberately CAPPED, which the two positive caches are not. A miss is cleared by a - * later successful load, which `resolveWithSchema` does not even attempt while one stands, or by - * an elasticsql DDL statement through THIS client ([[forgetSchemaMissesOf]]). An index created - * any other way — another client, a raw `PUT`, an ingest that auto-creates it — is not seen, so - * a miss remembered for an operator-chosen hour would leave every statement against it running - * with NO schema attached for that hour — no `SQLTypeUtils.coerce`, no temporal-literal - * resolution, silently (#306's skip conditions). Shortening the TTL still shortens this; making - * the knob able to LENGTHEN it would turn a five-minute nuisance into an unbounded one. + * later successful load, which `run` does not even attempt while one stands, or by an elasticsql + * DDL statement through THIS client ([[forgetSchemaMissesOf]]). An index created any other way — + * another client, a raw `PUT`, an ingest that auto-creates it — is not seen by `run`, so a miss + * remembered for an operator-chosen hour would leave every statement against it running with NO + * schema attached for that hour — no `SQLTypeUtils.coerce`, no temporal-literal resolution, + * silently (#306's skip conditions). Shortening the TTL still shortens this; making the knob + * able to LENGTHEN it would turn a five-minute nuisance into an unbounded one. + * + * R-169 -- `describe` never reads this TTL: it looks a remembered miss up again on every call + * ([[lookupSchema]]), and its successful lookup clears the miss, so the next `run` is typed. */ protected def schemaMissTtlMs: Long = math.min(schemaCacheTtlMs, SchemaCacheSettings.DefaultTtlMs) diff --git a/core/src/main/scala/app/softnetwork/elastic/client/SubqueryResolver.scala b/core/src/main/scala/app/softnetwork/elastic/client/SubqueryResolver.scala index 0f311013..440c57a1 100644 --- a/core/src/main/scala/app/softnetwork/elastic/client/SubqueryResolver.scala +++ b/core/src/main/scala/app/softnetwork/elastic/client/SubqueryResolver.scala @@ -98,7 +98,9 @@ object SubqueryResolver { resolve( single, s => api.search(s)(EntityContext), // an absent key stays ABSENT — never null-filled - api.scopeCorrelation(single, _), + // R-169 -- the scope check reads the mappings in the mode of the call: `describe` looks a + // remembered miss up again, `run` skips it (`SearchApi.lookupSchema`) + inner => api.scopeCorrelation(single, inner, describing = !executes), api.innerColumnType, executes ) diff --git a/core/src/test/scala/app/softnetwork/elastic/client/DescribeRememberedMissSpec.scala b/core/src/test/scala/app/softnetwork/elastic/client/DescribeRememberedMissSpec.scala new file mode 100644 index 00000000..44f6eab2 --- /dev/null +++ b/core/src/test/scala/app/softnetwork/elastic/client/DescribeRememberedMissSpec.scala @@ -0,0 +1,501 @@ +/* + * Copyright 2025 SOFTNETWORK + * + * Licensed 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 app.softnetwork.elastic.client + +import app.softnetwork.elastic.client.result._ +import app.softnetwork.elastic.sql.`type`.SQLTypes +import app.softnetwork.elastic.sql.parser.Parser +import app.softnetwork.elastic.sql.query.{MultiSearch, SelectStatement, SingleSearch, Statement} +import app.softnetwork.elastic.sql.schema.Schema +import org.scalatest.flatspec.AnyFlatSpec +import org.scalatest.matchers.should.Matchers +import org.slf4j.Logger +import org.slf4j.helpers.NOPLogger + +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicInteger + +/** SCHEMA-17 fix R-169 -- `describe` looks a remembered missing source up again, so it answers what + * `run` answers once the mapping is read: an index another client creates after a 404 was + * remembered (an ingest that auto-creates it, a raw `PUT`) is typed by the next describe, whose + * successful lookup forgets the miss, so the next `run` is typed too. `run` keeps its negative + * cache: no lookup while the miss stands. + * + * Population (spec section 4): source {one index, an alias, a pattern, a list, a pattern with a + * concrete part} x {created after the miss, still absent} x entry {describe(sql), + * describe(SingleSearch) reused, describe(SelectStatement) reused} x memo {cold, warm}; the other + * readers of the miss: `describePerTable`'s legs, `attachDerived`'s sources, a WHERE subquery's + * scope check, the legs of a UNION ALL. + * + * Docker-free: Elasticsearch is canned (`GET `, `_field_caps`, version 8.18.3), and an + * index is created "by another client" by adding it to [[CannedClient.existing]]: no DDL through + * the client, so no miss is forgotten by it. Every lookup the client makes is counted + * ([[CannedClient.lookupsOf]]), a cache hit included. + */ +class DescribeRememberedMissSpec extends AnyFlatSpec with Matchers { + + private val LongTtlMs = 3600000L + + private val tFields: Seq[(String, String)] = Seq( + "id" -> """{"type":"keyword"}""", + "k" -> """{"type":"keyword"}""", + "n" -> """{"type":"integer"}""", + "ts" -> """{"type":"date"}""" + ) + + /** `t` re-created by another client with another mapping. */ + private val tFieldsB: Seq[(String, String)] = Seq( + "id" -> """{"type":"keyword"}""", + "k" -> """{"type":"keyword"}""", + "n" -> """{"type":"long"}""", + "ts" -> """{"type":"date"}""", + "extra" -> """{"type":"double"}""" + ) + + private val uFields: Seq[(String, String)] = Seq( + "id" -> """{"type":"keyword"}""", + "m" -> """{"type":"integer"}""" + ) + + private val everything: Set[String] = Set("t", "t2", "u") + + private def properties(fields: Seq[(String, String)]): String = + fields.map { case (name, mapping) => s""""$name":$mapping""" }.mkString("{", ",", "}") + + private def doc(fields: Seq[(String, String)], aliases: String = "{}"): String = + s"""{"aliases":$aliases,"mappings":{"properties":${properties(fields)}},""" + + """"settings":{"index":{"number_of_shards":"1","number_of_replicas":"0"}}}""" + + /** Canned Elasticsearch over the indices that [[existing]] holds now: + * - `t` (its mapping [[fieldsOfT]]), `t2` (the same columns), `u` (another table); + * - `al` an alias over `t`, present with it; + * - a pattern matches the existing indices it prefixes (`t*`: `t`, `t2`), a comma list answers + * its members, and a concrete part that does not exist is a 404, as Elasticsearch answers; + * - `zz_*` matches nothing. + */ + final class CannedClient extends NopeClientApi { + @volatile var existing: Set[String] = Set.empty + @volatile var fieldsOfT: Seq[(String, String)] = tFields + @volatile var missTtlMs: Long = LongTtlMs + + private val lookups = new ConcurrentHashMap[String, AtomicInteger]() + + /** The lookups of `source` -- `SearchApi.lookupSchema`'s key -- made so far, cache hits + * included. + */ + def lookupsOf(source: String): Int = Option(lookups.get(source)).map(_.get()).getOrElse(0) + + override protected def logger: Logger = NOPLogger.NOP_LOGGER + + override protected def schemaCacheTtlMs: Long = LongTtlMs + + override protected def schemaMissTtlMs: Long = missTtlMs + + override private[client] def executeVersion(): ElasticResult[String] = + ElasticResult.success("8.18.3") + + override private[client] def loadQuerySchema(source: String): ElasticResult[Schema] = { + lookups.computeIfAbsent(source, _ => new AtomicInteger()).incrementAndGet() + super.loadQuerySchema(source) + } + + private def fieldsOf(index: String): Seq[(String, String)] = + index match { + case "t" => fieldsOfT + case "u" => uFields + case _ => tFields + } + + override private[client] def executeGetIndex(source: String): ElasticResult[Option[String]] = { + val now = existing + val (patterns, concrete) = source.split(",").map(_.trim).toSeq.partition(_.contains("*")) + val named = concrete.flatMap { + case "al" => if (now.contains("t")) Seq("t" -> """{"al":{}}""") else Nil + case name => if (now.contains(name)) Seq(name -> "{}") else Nil + } + val matched = patterns.flatMap { p => + val prefix = p.takeWhile(_ != '*') + now.toSeq.sorted.filter(_.startsWith(prefix)).map(_ -> "{}") + } + val members = (named ++ matched).distinct + if (named.size < concrete.size || members.isEmpty) ElasticResult.success(None) + else + ElasticResult.success( + Some( + members + .map { case (index, aliases) => s""""$index":${doc(fieldsOf(index), aliases)}""" } + .mkString("{", ",", "}") + ) + ) + } + + override private[client] def executeFieldCaps(source: String): ElasticResult[Option[String]] = + ElasticResult.success(None) + } + + private def client( + existing: Set[String] = Set.empty, + fieldsOfT: Seq[(String, String)] = tFields + ): CannedClient = { + val c = new CannedClient + c.existing = existing + c.fieldsOfT = fieldsOfT + c + } + + type Answer = ElasticResult[Option[ResultSchema]] + + private def parse(sql: String): Statement = + Parser(sql) match { + case Right(statement) => statement + case Left(error) => fail(s"[$sql] does not parse: ${error.msg}") + } + + private def single(sql: String): SingleSearch = + parse(sql) match { + case s: SingleSearch => s + case s: SelectStatement => + s.statement match { + case Some(inner: SingleSearch) => inner + case other => fail(s"[$sql] is not a single search: $other") + } + case other => fail(s"[$sql] is not a single search: $other") + } + + /** How a consumer calls describe; `memoized`: the memo reaches it (A-190). */ + final case class Entry( + name: String, + memoized: Boolean, + caller: (CannedClient, String) => () => Answer + ) + + private val bySql = Entry("describe(sql)", memoized = false, (c, sql) => () => c.describe(sql)) + + private val reusedSingle = + Entry( + "describe(SingleSearch) reused", + memoized = true, + (c, sql) => { + val statement = single(sql) + () => c.describe(statement) + } + ) + + private val reusedSelect = + Entry( + "describe(SelectStatement) reused", + memoized = true, + (c, sql) => { + val statement = SelectStatement(sql) + () => c.describe(statement) + } + ) + + private val entries = Seq(bySql, reusedSingle, reusedSelect) + + /** (label, source): every source shape, keyed as the miss is (the sources joined by commas). */ + private val sources: Seq[(String, String)] = Seq( + "one index" -> "t", + "an alias" -> "al", + "a pattern" -> "t*", + "a list" -> "t,t2", + "a pattern with a concrete part" -> "zz_*,t" + ) + + private def statements(source: String): Seq[String] = Seq( + s"SELECT * FROM $source", + s"SELECT id, k, n, ts FROM $source" + ) + + private def renderColumn(c: ResultColumn): String = { + val fields = if (c.fields.isEmpty) "" else c.fields.map(renderColumn).mkString("{", ",", "}") + val element = c.element.fold("")(e => "[" + renderColumn(e) + "]") + s"${c.name}:${c.sqlType.typeId}${if (c.nullable) "" else " NOT NULL"}$fields$element" + } + + /** An answer, compared across clients: the schema, or the refusal with its status. */ + private def render(answer: Answer): String = + answer match { + case ElasticSuccess(Some(schema)) => + schema.columns.map(renderColumn).mkString("SOME(", ",", ")") + case ElasticSuccess(None) => "NONE" + case ElasticFailure(error) => + s"FAILURE(${error.statusCode.getOrElse(-1)}|${error.operation.getOrElse("")}|" + + s"${error.index.getOrElse("")}|${error.message})" + } + + /** The answer a FRESH client -- no miss remembered -- gives `sql` over `existing`. */ + private def fresh( + sql: String, + existing: Set[String], + fieldsOfT: Seq[(String, String)] = tFields + ): String = + render(client(existing, fieldsOfT).describe(sql)) + + /** Both successes, and the very same answer instance: answered from memory. */ + private def sameAnswer(a: Answer, b: Answer): Boolean = + (a, b) match { + case (ElasticSuccess(x), ElasticSuccess(y)) => + x.asInstanceOf[AnyRef] eq y.asInstanceOf[AnyRef] + case _ => false + } + + /** Whether `run`'s resolution (`executeSubqueries = true`) attaches a schema with columns. */ + private def typedByRun(c: CannedClient, sql: String): Boolean = + c.resolveWithSchema(single(sql)) match { + case ElasticSuccess(sent) => sent.schema.exists(_.columns.nonEmpty) + case other => fail(s"run's resolution of [$sql]: $other") + } + + // --------------------------------------------------------------------------------------------- + // AC1 / AC3 -- created after the miss: describe types it, run is typed after describe + // --------------------------------------------------------------------------------------------- + + "describe" should "type a source another client created after its 404 was remembered, and run after it (AC1, AC3)" in { + for { + entry <- entries + (label, source) <- sources + sql <- statements(source) + } withClue(s"[${entry.name} | $label | $sql] ") { + val c = client() + val call = entry.caller(c, sql) + // the 404 -- or, for a pattern of `*` parts, the empty table -- remembered by the lookup + val before = call() + render(before) shouldBe fresh(sql, Set.empty) + c.schemaMissCount shouldBe 1 + c.existing = everything // created by another client: the miss stands + // AC3 -- run keeps its negative cache: no lookup, untyped + val looked = c.lookupsOf(source) + typedByRun(c, sql) shouldBe false + c.lookupsOf(source) shouldBe looked + // AC1 -- describe looks it up again: typed, as a fresh client types it + val after = call() + render(after) should startWith("SOME(") + render(after) should not be render(before) + render(after) shouldBe fresh(sql, everything) + c.lookupsOf(source) shouldBe looked + 1 + // the success forgot the miss: the next run is typed + c.schemaMissCount shouldBe 0 + typedByRun(c, sql) shouldBe true + // AC5 -- memo warm after the transition: the typed answer from memory + if (entry.memoized) { + sameAnswer(after, call()) shouldBe true + c.describeAnswerCount shouldBe 1 + } else c.describeAnswerCount shouldBe 0 + } + } + + it should "type the legs of a UNION ALL created after the first leg's 404 was remembered (AC1)" in { + val sql = "SELECT id, n FROM t UNION ALL SELECT id, n FROM t2" + val reusedStatement = + Entry( + "describe(Statement) reused", + memoized = false, + (c, s) => { + val statement = parse(s) + () => c.describe(statement) + } + ) + for (entry <- Seq(bySql, reusedStatement)) withClue(s"[${entry.name}] ") { + val c = client() + val call = entry.caller(c, sql) + render(call()) should startWith("FAILURE(404|describe|") + c.existing = everything + val after = call() + render(after) should startWith("SOME(") + render(after) shouldBe fresh(sql, everything) + c.schemaMissCount shouldBe 0 + } + } + + // --------------------------------------------------------------------------------------------- + // AC2 / AC6 -- still absent: the 404, looked up on every describe, the miss re-armed + // --------------------------------------------------------------------------------------------- + + it should "answer a source still absent with its 404, looking it up on every describe (AC2, AC6)" in { + for { + entry <- entries + source <- Seq("t", "al", "t,t2", "zz_*,t") + } withClue(s"[${entry.name} | $source] ") { + val existing = Set("t2", "u") // `t` absent + val c = client(existing) + val sql = s"SELECT id FROM $source" + val call = entry.caller(c, sql) + (1 to 3).foreach { i => + val answer = call() + render(answer) shouldBe fresh(sql, existing) + render(answer) should startWith("FAILURE(404|describe|") + render(answer) should endWith(s"|no such index [$source])") + // one lookup per describe: no negative caching on describe's path + c.lookupsOf(source) shouldBe i + } + // never memoized (A-192), the miss remembered for run + c.describeAnswerCount shouldBe 0 + c.schemaMissCount shouldBe 1 + typedByRun(c, sql) shouldBe false + c.lookupsOf(source) shouldBe 3 + } + } + + it should "type a pattern of `*` parts matching nothing as an empty table on every describe (AC2, A-163 b)" in { + for { + entry <- entries + sql <- Seq("SELECT * FROM zz_*", "SELECT id FROM zz_*") + } withClue(s"[${entry.name} | $sql] ") { + val c = client(everything) + val call = entry.caller(c, sql) + (1 to 3).foreach { i => + val answer = call() + render(answer) should startWith("SOME(") + render(answer) shouldBe fresh(sql, everything) + // one lookup per describe, the 404 behind the empty table remembered for run + c.lookupsOf("zz_*") shouldBe i + c.schemaMissCount shouldBe 1 + } + if (sql.startsWith("SELECT *")) render(call()) shouldBe "SOME()" + } + } + + it should "remember the miss afresh on each describe of an absent source (AC2)" in { + val sql = "SELECT id FROM t" + val c = client() + render(c.describe(sql)) should startWith("FAILURE(404|describe|") + Thread.sleep(1500) + render(c.describe(sql)) should startWith("FAILURE(404|describe|") + // a miss 1 s old stands, one 1.5 s old would not: the second describe re-armed it + c.missTtlMs = 1000L + val looked = c.lookupsOf("t") + typedByRun(c, sql) shouldBe false + c.lookupsOf("t") shouldBe looked + // the control: once that miss is older than the TTL too, run looks the source up again + Thread.sleep(1100) + typedByRun(c, sql) shouldBe false + c.lookupsOf("t") shouldBe looked + 1 + } + + // --------------------------------------------------------------------------------------------- + // AC5 -- the memo across the transition + // --------------------------------------------------------------------------------------------- + + it should "answer a miss remembered over a cached schema from that schema, from memory when warm (AC5)" in { + for (entry <- entries) withClue(s"[${entry.name}] ") { + val sql = "SELECT * FROM t" + val c = client(everything) + val call = entry.caller(c, sql) + val first = call() + render(first) shouldBe fresh(sql, everything) + // the testkit's seam: a miss remembered while the schema is cached + c.rememberSchemaMiss("t") + val second = call() + render(second) shouldBe render(first) + sameAnswer(first, second) shouldBe entry.memoized + c.schemaMissCount shouldBe 0 + typedByRun(c, sql) shouldBe true + } + } + + it should "never store a 404, and store the typed answer under the new schema once the index appears (AC5)" in { + for (entry <- entries.filter(_.memoized)) withClue(s"[${entry.name}] ") { + val sql = "SELECT * FROM t" + val c = client() + val call = entry.caller(c, sql) + render(call()) should startWith("FAILURE(404|") + render(call()) should startWith("FAILURE(404|") + c.describeAnswerCount shouldBe 0 + // created by another client + c.existing = everything + val typedA = call() + render(typedA) shouldBe fresh(sql, everything) + sameAnswer(typedA, call()) shouldBe true + c.describeAnswerCount shouldBe 1 + // dropped through this client, then re-created by another one with another mapping + c.existing = Set("t2", "u") + c.invalidateSchema("t") + render(call()) should startWith("FAILURE(404|") + c.fieldsOfT = tFieldsB + c.existing = everything + val typedB = call() + render(typedB) shouldBe fresh(sql, everything, tFieldsB) + render(typedB) should include("extra:") + render(typedB) should not be render(typedA) + sameAnswer(typedA, typedB) shouldBe false + sameAnswer(typedB, call()) shouldBe true + c.describeAnswerCount shouldBe 1 + } + } + + // --------------------------------------------------------------------------------------------- + // AC4 -- the other readers of the miss, in describe's mode + // --------------------------------------------------------------------------------------------- + + it should "type a JOIN body per table once its remembered missing leg exists, None while absent (describePerTable)" in { + val sql = "SELECT a.id, a.n, b.m FROM t a JOIN u b ON a.id = b.id" + val statement = parse(sql) + val c = client(Set("t", "t2")) + c.describePerTable(statement) shouldBe ElasticSuccess(None) + c.lookupsOf("u") shouldBe 1 + c.schemaMissCount shouldBe 1 + // still absent: read again, still None + c.describePerTable(statement) shouldBe ElasticSuccess(None) + c.lookupsOf("u") shouldBe 2 + c.schemaMissCount shouldBe 1 + // created by another client + c.existing = everything + val typed = c.describePerTable(statement) + render(typed) should startWith("SOME(") + render(typed) shouldBe render(client(everything).describePerTable(parse(sql))) + c.schemaMissCount shouldBe 0 + } + + it should "type a derived body over an index created after its 404 was remembered (attachDerived)" in { + val sql = "SELECT q.c1 FROM (SELECT n AS c1 FROM t) q" + val c = client() + render(c.describe("SELECT n FROM t")) should startWith("FAILURE(404|") + c.schemaMissCount shouldBe 1 + c.existing = everything + c.attachDerived(single(sql)) match { + case ElasticSuccess(attached) => + MultiSearch.projectionTypes(attached).map(_.map(_._2.sqlType)) shouldBe Some( + Seq(SQLTypes.Int) + ) + case other => fail(s"attachDerived: $other") + } + c.schemaMissCount shouldBe 0 + } + + it should "scope a WHERE subquery by an inner index created after its 404 was remembered, as run then does" in { + val sql = "SELECT id FROM t WHERE id IN (SELECT id FROM u WHERE k = 'x')" + val oracle = fresh(sql, everything) + // the oracle: with both mappings read, `k` -- mapped by `t`, not by `u` -- is a correlation + oracle should startWith("FAILURE(400|") + oracle should include("'k' is not a column of 'u'") + val c = client(everything) + c.rememberSchemaMiss("u") + val outer = single(sql) + val inner = outer.whereSubqueries.head.inner.getOrElse(fail("no body")) + // run's scope check keeps the miss: no lookup, no refusal + c.scopeCorrelation(outer, inner) shouldBe None + c.lookupsOf("u") shouldBe 0 + // describe's scope check reads `u` again: run's refusal + render(c.describe(sql)) shouldBe oracle + c.schemaMissCount shouldBe 0 + // the success forgot the miss: run's scope check refuses too + c.scopeCorrelation(outer, inner).getOrElse(fail("expected run's refusal")) should include( + "'k' is not a column of 'u'" + ) + } +} diff --git a/documentation/client/gateway.md b/documentation/client/gateway.md index f066f5a0..01ef785d 100644 --- a/documentation/client/gateway.md +++ b/documentation/client/gateway.md @@ -219,7 +219,9 @@ message. *Since `0.25.0`*, one rule for every consumer: name typed over the legs that carry it), an alias or a data stream over several indices from its members; - a failure: refused with the status `run` answers -- an unknown index is a `404`, a mapping read - that fails otherwise keeps its status (`operation = "describe"`; it answered `None` before); + that fails otherwise keeps its status (`operation = "describe"`; it answered `None` before). An + index found missing is read again on every `describe`, so one another client creates afterwards + (an ingest that auto-creates it, a raw `PUT`) is typed at once, and the next `run` with it; - `ElasticSuccess(None)`: only for a statement another extension than core's handles (a cross-index JOIN under the arrow extension), whose own layer types it. diff --git a/documentation/client/search.md b/documentation/client/search.md index 7ec227fe..dde30e2f 100644 --- a/documentation/client/search.md +++ b/documentation/client/search.md @@ -1593,7 +1593,11 @@ creates, alters or drops a table (`CREATE TABLE`, a partitioned `CREATE TABLE`'s TABLE`, `DROP TABLE`, `createIndex`, `deleteIndex`, the REPL `refresh`) forgets the misses it makes stale at once — the table's own and those of every pattern or list it matches — so a table created after a query found it missing is typed by the next statement. An index created any other way -(another client, a raw `PUT`, an ingest that creates it) is seen when the miss expires. +(another client, a raw `PUT`, an ingest that creates it) is seen when the miss expires — or at the +next `describe` (*since `0.25.0`*): `describe` never skips a lookup for a remembered miss, so it +answers what `run` will answer, and its successful lookup forgets the miss. A `describe` of an index +that is still absent therefore repeats the failed lookup on every call: a `GET ` and a lookup +of the template of that name, two round trips logged as several WARN lines. ## Performance Optimization diff --git a/testkit/src/main/scala/app/softnetwork/elastic/client/DescribeRunParitySpec.scala b/testkit/src/main/scala/app/softnetwork/elastic/client/DescribeRunParitySpec.scala index 304af9a2..26c10d6f 100644 --- a/testkit/src/main/scala/app/softnetwork/elastic/client/DescribeRunParitySpec.scala +++ b/testkit/src/main/scala/app/softnetwork/elastic/client/DescribeRunParitySpec.scala @@ -32,6 +32,7 @@ import app.softnetwork.elastic.client.spi.ElasticClientFactory import app.softnetwork.elastic.scalatest.ElasticDockerTestKit import app.softnetwork.elastic.sql.`type`.{SQLType, SQLTypes} import app.softnetwork.elastic.sql.parser.Parser +import app.softnetwork.elastic.sql.query.SingleSearch import app.softnetwork.persistence.generateUUID import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} import org.apache.http.entity.ContentType @@ -98,8 +99,10 @@ trait DescribeRunParitySpec extends AnyFlatSpecLike with ElasticDockerTestKit wi private val al1 = "p17al1" private val al2 = "p17al2" private val alc = "p17alc" + // R-169: created by another client after its 404 was remembered + private val late = "p17late" - private def indices: Seq[String] = Seq(idxA, idxB, idxC, dn, s, sc, f, g) + private def indices: Seq[String] = Seq(idxA, idxB, idxC, dn, s, sc, f, g, late) private val abMapping = """{"_meta": {"columns": {"tags": {"data_type": "ARRAY"}}}, @@ -396,6 +399,85 @@ trait DescribeRunParitySpec extends AnyFlatSpecLike with ElasticDockerTestKit wi parity("SELECT * FROM p17nomatch_*,p17gone") } + // ------------------------------------------------------------------------------------------- + // R-169 -- a remembered 404: describe looks the source up again, run keeps its negative cache + // ------------------------------------------------------------------------------------------- + + @scala.annotation.tailrec + private def baseClientOf(c: ElasticClientApi): ElasticClientApi = c match { + case delegator: ElasticClientDelegator => baseClientOf(delegator.delegate) + case other => other + } + + /** Whether `run`'s resolution attaches a schema with columns (on the base client, whose map of + * remembered misses it reads); false while a miss stands, since `run` makes no lookup then. + */ + private def typedByRun(sql: String): Boolean = + Parser(sql) match { + case Right(single: SingleSearch) => + baseClientOf(client).resolveWithSchema(single) match { + case ElasticSuccess(sent) => sent.schema.exists(_.columns.nonEmpty) + case other => fail(s"run's resolution of [$sql]: $other") + } + case other => fail(s"[$sql] is not a single search: $other") + } + + it should "type an index another client created after its 404 was remembered, as run then answers (R-169)" in { + val sql = s"SELECT k, n FROM $late" + // the 404, remembered by the lookup + client.describe(sql) match { + case ElasticFailure(error) => error.statusCode shouldBe Some(404) + case other => fail(s"expected the 404, got $other") + } + // another client creates it: an ingest that auto-creates the index, no DDL through this client + val created = raw("POST", s"/$late/_doc?refresh=true", Some("""{"k":"l1","n":7}"""))._1 + created should (be(200) or be(201)) + // run, while the miss stands, makes no lookup: untyped + typedByRun(sql) shouldBe false + // describe looks it up again, by text and by statement + val declared = described(sql) + declared.columns.map(_.name) shouldBe Seq("k", "n") + declared.columns.find(_.name == "n").map(_.sqlType) shouldBe Some(SQLTypes.BigInt) + Parser(sql) match { + case Right(statement) => client.describe(statement) shouldBe ElasticSuccess(Some(declared)) + case Left(error) => fail(s"[$sql] does not parse: ${error.msg}") + } + // its success forgot the miss: run is typed, and answers what describe declared + typedByRun(sql) shouldBe true + parity(sql) + } + + it should "type an alias, a pattern and a list whose miss is remembered over their cached schema (R-169)" in { + Seq(al1, al2, "p17x_*", s"$idxA,$idxC").foreach { source => + val sql = s"SELECT k, n FROM $source" + withClue(s"[$sql] ") { + val expected = described(sql) + baseClientOf(client).rememberSchemaMiss(source) + typedByRun(sql) shouldBe false + described(sql) shouldBe expected + typedByRun(sql) shouldBe true + parity(sql) + } + } + } + + it should "keep a source still absent a 404 on every describe, and a pattern matching none an empty table (R-169)" in { + val gone = "p17never" + (1 to 2).foreach { _ => + client.describe(s"SELECT k FROM $gone") match { + case ElasticFailure(error) => + error.statusCode shouldBe Some(404) + error.operation shouldBe Some("describe") + error.message shouldBe s"no such index [$gone]" + case other => fail(s"expected the 404, got $other") + } + } + parity(s"SELECT k FROM $gone") + baseClientOf(client).rememberSchemaMiss("p17nomatch_*") + described("SELECT * FROM p17nomatch_*") shouldBe ResultSchema(Nil) + parity("SELECT * FROM p17nomatch_*") + } + // ------------------------------------------------------------------------------------------- // U1 -- SELECT * legs of a UNION ALL (A-165) // ------------------------------------------------------------------------------------------- diff --git a/testkit/src/main/scala/app/softnetwork/elastic/client/PerTableDescribeSpec.scala b/testkit/src/main/scala/app/softnetwork/elastic/client/PerTableDescribeSpec.scala index 3dbe0ddd..536dedcf 100644 --- a/testkit/src/main/scala/app/softnetwork/elastic/client/PerTableDescribeSpec.scala +++ b/testkit/src/main/scala/app/softnetwork/elastic/client/PerTableDescribeSpec.scala @@ -24,6 +24,8 @@ import app.softnetwork.elastic.sql.parser.Parser import app.softnetwork.elastic.sql.query.Statement import app.softnetwork.persistence.generateUUID import com.fasterxml.jackson.databind.ObjectMapper +import org.apache.http.entity.ContentType +import org.apache.http.nio.entity.NStringEntity import org.apache.http.util.EntityUtils import org.elasticsearch.client.Request import org.scalatest.flatspec.AnyFlatSpecLike @@ -64,6 +66,11 @@ trait PerTableDescribeSpec extends AnyFlatSpecLike with ElasticDockerTestKit wit private def indices: Seq[String] = Seq(ptA, ptB, ptAB) + /** R-169: a leg created by another client after its 404 was remembered (never in [[indices]], + * whose `_stats` it would fail while absent). + */ + protected val ptLate = "pt_late" + protected def ptAColumns: Seq[(String, String)] = Seq( "aid" -> """{"type": "keyword"}""", "bid" -> """{"type": "keyword"}""", @@ -130,7 +137,7 @@ trait PerTableDescribeSpec extends AnyFlatSpecLike with ElasticDockerTestKit wit override def beforeAll(): Unit = { super.beforeAll() - indices.foreach(drop) + (indices :+ ptLate).foreach(drop) load( ptA, mappingOf(ptAColumns, withMeta = true), @@ -158,7 +165,7 @@ trait PerTableDescribeSpec extends AnyFlatSpecLike with ElasticDockerTestKit wit } override def afterAll(): Unit = { - indices.foreach(drop) + (indices :+ ptLate).foreach(drop) super.afterAll() } @@ -295,4 +302,19 @@ trait PerTableDescribeSpec extends AnyFlatSpecLike with ElasticDockerTestKit wit } queryTotal() should be > before } + + it should "type a leg another client created after its 404 was remembered (R-169)" in { + val body = parsed(s"SELECT a.aid, l.w FROM $ptA a JOIN $ptLate l ON a.bid = l.bid") + // the leg's 404, remembered by the lookup: no schema + client.describePerTable(body) shouldBe ElasticSuccess(None) + // another client creates it: an ingest that auto-creates the index, no DDL through this client + val request = new Request("POST", s"/$ptLate/_doc?refresh=true") + request.setEntity(new NStringEntity("""{"bid":"b1","w":1}""", ContentType.APPLICATION_JSON)) + restClient.performRequest(request).getStatusLine.getStatusCode should (be(200) or be(201)) + // describePerTable reads the leg again: typed, each column as over its own table + val typed = columnsOf(client.describePerTable(body)) + typed shouldBe columnsOf(client.describe(s"SELECT aid FROM $ptA")) ++ + columnsOf(client.describe(s"SELECT w FROM $ptLate")) + typed.map(_._2) should not contain "ANY" + } }