Skip to content

[Bug]: MongoDB external scan follow-ups after #26424 #26485

Closed

Description

@XuPeng-SH

Summary

PR #26424 introduced MongoDB external table scans and was merged as
cf6dca31107769ad7855ebb45b1a6b48298284d6. A post-merge first-principles
review found several independently reproducible production issues across
authorization, temporal correctness, memory admission, snapshot/PITR
consistency, and max_by complexity. The connector's required CI passed, but
the cases below are outside the current test matrix.

This is an umbrella follow-up issue. Each checked item should be closed only
after its regression test and production fix land.

Confirmed production issues

  • Authorization boundary can be bypassed through generic external-table
    metadata.

    ParseCreateSQLEnvelope searches the entire rel_createsql string for
    MO_MONGODB:. Generic external-table options, including user-controlled
    filepath values, are serialized into the same field. Authentication checks
    account-admin only when the original AST has MongoDBParam != nil, while
    compile and query planning classify the persisted metadata by the loose
    marker. A normal CREATE TABLE holder can therefore cause a generic
    external table to use an administrator-created MongoDB connection.

    References:

    • func ParseCreateSQLEnvelope(ctx context.Context, createSQL string) (CreateSQLEnvelope, bool, error) {
      idx := strings.Index(createSQL, CreateSQLEnvelopePrefix)
      if idx < 0 {
      return CreateSQLEnvelope{}, false, nil
      }
      start := idx + len(CreateSQLEnvelopePrefix)
      end := strings.Index(createSQL[start:], "*/")
      if end < 0 {
      return CreateSQLEnvelope{}, true, moerr.NewInvalidInput(ctx, "MongoDB rel_createsql envelope is not closed")
      }
      fields := make(map[string]string)
      for _, part := range strings.Split(createSQL[start:start+end], ";") {
    • if ses.GetTenantInfo() != nil {
      ses.SetPrivilege(determinePrivilegeSetOfStatement(stmt))
      if !canCreateMongoDBTableMapping(stmt, ses.GetTenantInfo()) {
      // The privilege model has no external-connection USAGE object yet.
      // Fail closed instead of letting any ordinary CREATE TABLE holder use
      // an administrator's connection against an arbitrary collection.
      return stats, moerr.NewInternalError(reqCtx, "MongoDB external table creation requires account admin until connection USAGE privileges are available")
      }
      // can or not execute in retricted status
      if ses.getRoutine() != nil && ses.getRoutine().isRestricted() && !ses.GetPrivilege().canExecInRestricted {
      return stats, moerr.NewInternalError(reqCtx, "do not have enough storage to execute the statement")
      }
      // can or not execute in password expired status
      if ses.getRoutine() != nil && ses.getRoutine().isExpired() && !ses.GetPrivilege().canExecInPasswordExpired {
      return stats, moerr.NewInternalError(reqCtx, "password has expired, please change the password")
      }
      havePrivilege, delta, err := authenticateUserCanExecuteStatementWithObjectTypeAccountAndDatabase(reqCtx, ses, stmt)
      if err != nil {
      return stats, err
      }
      stats.Add(&delta)
      if !havePrivilege {
      err = moerr.NewInternalError(reqCtx, "do not have privilege to execute the statement")
      return stats, err
      }
      havePrivilege, delta, err = authenticateUserCanExecuteStatementWithObjectTypeNone(reqCtx, ses, stmt)
      if err != nil {
      return stats, err
      }
      stats.Add(&delta)
      if !havePrivilege {
      err = moerr.NewInternalError(reqCtx, "do not have privilege to execute the statement")
      return stats, err
      }
      //!!!note: clone table executed in the frontend.
      //handle privilege check here for it
      priv := ses.GetPrivilege()
      if priv.objectType() == objectTypeTable {
      if !checkProtectedDatabaseWriteByPrivilege(reqCtx, ses, priv) {
      return stats, moerr.NewInternalError(reqCtx, "do not have privilege to execute the statement")
      }
      }
      }
      return stats, nil
      }
      func canCreateMongoDBTableMapping(stmt tree.Statement, tenant *TenantInfo) bool {
      create, ok := stmt.(*tree.CreateTable)
      if !ok || create.MongoDBParam == nil {
      return true
      }
      return tenant != nil && tenant.IsAdminRole()
    • } else if stmt.Param != nil {
      for i := 0; i < len(stmt.Param.Option); i += 2 {
      switch strings.ToLower(stmt.Param.Option[i]) {
      case "endpoint", "region", "access_key_id", "secret_access_key", "bucket", "filepath", "compression", "format", "jsondata", "provider", "role_arn", "external_id", "hive_partitioning", "hive_partition_columns", ExternalWriteFilePatternKey, CSVCommentKey:
      default:
      return nil, moerr.NewBadConfigf(ctx.GetContext(), "the keyword '%s' is not support", strings.ToLower(stmt.Param.Option[i]))
      }
      }
      if err := validateWriteFilePattern(ctx.GetContext(), stmt.Param, createTable.TableDef); err != nil {
      return nil, err
      }
      if err := validateAndSetHivePartitionOptions(ctx.GetContext(), stmt, createTable); err != nil {
      return nil, err
      }
      if err := InitNullMap(stmt.Param, ctx); err != nil {
      return nil, err
      }
      json_byte, err := json.Marshal(stmt.Param)
      if err != nil {
      return nil, err
      }
      properties := []*plan.Property{
      {
      Key: catalog.SystemRelAttr_Kind,
      Value: catalog.SystemExternalRel,
      },
      {
      Key: catalog.SystemRelAttr_CreateSQL,
      Value: string(json_byte),
      },
      }
      createTable.TableDef.TableType = catalog.SystemExternalRel
    • func (c *Compile) maybeInsertMongoDBTableMapping(dbSource engine.Database, rel engine.Relation, qry *plan.CreateTable) error {
      createSQL := icebergCreateSQLFromPlanTableDef(qry.GetTableDef())
      env, found, err := sqlmongodb.ParseCreateSQLEnvelope(c.proc.Ctx, createSQL)
      if err != nil || !found {
      return err
      }
      accountID, err := defines.GetAccountId(c.proc.Ctx)
      if err != nil {
      return err
      }
      dbIDText := dbSource.GetDatabaseId(c.proc.Ctx)
      dbID, err := strconv.ParseUint(dbIDText, 10, 64)
      if err != nil || dbID == 0 {
      return moerr.NewInternalErrorf(c.proc.Ctx, "invalid database id for MongoDB mapping: %s", dbIDText)
      }
      connectionID, err := c.lookupMongoDBConnectionID(accountID, env.Connection)
      if err != nil {
      return err
      }
      mapping := sqlmongodb.TableMapping{
      AccountID: accountID, DatabaseID: dbID, TableID: rel.GetTableID(c.proc.Ctx),
      ConnectionID: connectionID, Connection: env.Connection,
      Database: env.Database, Collection: env.Collection,
      SchemaMode: env.SchemaMode, Conversion: env.ConversionMode,
      SplitKey: env.SplitKey, MaxParallelism: env.MaxParallelism,
      Columns: env.Columns, Version: 1,
      }
      return c.runSqlWithOptions(
      sqlmongodb.InsertTableMappingSQL(mapping),
      executor.StatementOption{}.WithDisableLog(),
      )
  • Temporal predicate pushdown produces false negatives for
    DATETIME/TIMESTAMP(0..2).

    Pushdown eligibility ignores the mapped column scale. For example, BSON
    10.100s normalizes to DATETIME(0) = 10s, so the MO residual accepts it,
    but the pushed Mongo equality is {ts: 10.000s} and discards the document
    before the residual runs.

    Reproduction result: source=10100 candidate=10000.

    Reference:

    func eligibleComparisonColumn(column *plan.MongoColumnMapping) bool {
    if column == nil || !strings.EqualFold(column.ConversionMode, ConversionTryNull) {
    return false
    }
    switch types.T(column.MoType.Id) {
    case types.T_bool,
    types.T_int8, types.T_int16, types.T_int32, types.T_int64,
    types.T_uint8, types.T_uint16, types.T_uint32, types.T_uint64,
    types.T_datetime, types.T_timestamp:
    return true
    default:
    // BSON int64/double values can collapse to the same FLOAT after
    // float32 narrowing or float64's >2^53 rounding. Pushing the SQL
    // comparison against the pre-conversion BSON value can then remove a
    // row that the residual comparison would accept. Keep floating-point
    // mappings residual-only until an outward-rounded candidate predicate
    // is implemented and differentially proven.
    return false
    }
    }
    func comparisonPlanLiteral(column *plan.MongoColumnMapping, expr *plan.Expr, op PredicateOp) (any, bool) {
    if column == nil || expr == nil {
    return nil, false
    }
    switch types.T(column.MoType.Id) {
    case types.T_datetime, types.T_timestamp:
    microseconds, ok := temporalLiteralUnixMicroseconds(expr)
    if !ok {
    return nil, false
    }
    milliseconds, ok := temporalCandidateMilliseconds(microseconds, op)
    if !ok {
    return nil, false
    }
    return bson.DateTime(milliseconds), true

  • BSON DateTime conversion accepts invalid values, can overflow, and
    does not honor TIMESTAMP scale.

    Conversion performs millisecond-to-microsecond arithmetic before validating
    the MO temporal domain. Reproductions:

    • year 10000 is accepted as an invalid DATETIME;
    • BSON DateTime math.MaxInt64 wraps to 1969-12-31 23:59:59;
    • BSON .100 remains fractional inside TIMESTAMP(0).

    Reference:

    case types.T_date, types.T_datetime, types.T_timestamp:
    millis, ok := value.DateTimeOK()
    if !ok {
    return errConversion
    }
    dt := types.DatetimeFromUnixWithNsec(time.UTC, millis/1000, (millis%1000)*int64(time.Millisecond))
    switch target {
    case types.T_date:
    return vector.AppendFixed(vec, dt.ToDate(), false, mp)
    case types.T_datetime:
    return vector.AppendFixed(vec, dt.TruncateToScale(column.Scale), false, mp)
    default:
    return vector.AppendFixed(vec, dt.ToTimestamp(time.UTC), false, mp)
    }

  • Raw BSON batch limits do not bound decoded/vector memory.

    MaxBatchBytes counts only raw BSON. The converter separately copies a
    varlen value into every mapped output vector, and multiple columns may map
    the same BSON path. A diagnostic test expanded one 256 KiB value mapped to
    64 columns into 16,778,752 bytes of vector allocation. With up to 4096
    columns, a legal near-16 MiB document has a tens-of-GiB theoretical peak.

    References:

    • maxBatchBytes := deps.Config.MaxBatchBytes
      if maxBatchBytes <= 0 {
      maxBatchBytes = mongodb.DefaultRuntimeConfig().MaxBatchBytes
      }
      maxRows := firstPositive(scan.Scan.MaxScanRows, deps.Config.MaxScanRows)
      maxBytes := firstPositive(scan.Scan.MaxScanBytes, deps.Config.MaxScanBytes)
      bat := scan.ctr.converter.NewBatch()
      var currentBatchBytes int64
      for bat.RowCount() < batchRows {
      var raw []byte
      if scan.ctr.pendingRaw != nil {
      raw = scan.ctr.pendingRaw
      scan.ctr.pendingRaw = nil
      } else {
      waitStarted := time.Now()
      if !scan.ctr.cursor.Next(proc.Ctx) {
      process.StopAnalyzerWait(scan.OpAnalyzer, waitStarted, resource.WaitRemote)
      metric.MongoDBPhaseDurationHistogram.WithLabelValues("get_more_wait").Observe(time.Since(waitStarted).Seconds())
      if cursorErr := scan.ctr.cursor.Err(); cursorErr != nil {
      metric.MongoDBCursorEventCounter.WithLabelValues("error").Inc()
      bat.Clean(proc.Mp())
      scan.ctr.done = true
      scan.closeResources(proc.Ctx)
      return result, moerr.NewInternalError(proc.Ctx, "MongoDB cursor failed")
      }
      scan.ctr.done = true
      scan.closeResources(proc.Ctx)
      break
      }
      process.StopAnalyzerWait(scan.OpAnalyzer, waitStarted, resource.WaitRemote)
      metric.MongoDBPhaseDurationHistogram.WithLabelValues("get_more_wait").Observe(time.Since(waitStarted).Seconds())
      raw = scan.ctr.cursor.CurrentRaw()
      }
      if int64(len(raw)) > maxBatchBytes || currentBatchBytes+int64(len(raw)) > maxBatchBytes && bat.RowCount() == 0 {
      bat.Clean(proc.Mp())
      scan.ctr.done = true
      scan.closeResources(proc.Ctx)
      return result, moerr.NewInvalidInput(proc.Ctx, "MongoDB batch byte limit exceeded")
      }
      if currentBatchBytes+int64(len(raw)) > maxBatchBytes {
      // A cursor cannot unread, so retain exactly one bounded document for
      // the next Call. Copy because driver-owned Current is reused by Next.
      scan.ctr.pendingRaw = append(scan.ctr.pendingRaw[:0], raw...)
      break
      }
      decodeStarted := time.Now()
      if err = scan.ctr.converter.AppendDocument(proc.Ctx, bat, raw, proc.Mp()); err != nil {
      metric.MongoDBPhaseDurationHistogram.WithLabelValues("decode_append").Observe(time.Since(decodeStarted).Seconds())
      bat.Clean(proc.Mp())
      scan.ctr.done = true
      scan.closeResources(proc.Ctx)
      return result, err
      }
      metric.MongoDBPhaseDurationHistogram.WithLabelValues("decode_append").Observe(time.Since(decodeStarted).Seconds())
      metric.MongoDBScanDocumentsCounter.Inc()
      metric.MongoDBScanRawBytesCounter.Add(float64(len(raw)))
      currentBatchBytes += int64(len(raw))
    • func (c *Converter) AppendDocument(ctx context.Context, bat *batch.Batch, raw []byte, mp *mpool.MPool) error {
      if int64(len(raw)) > c.maxValueBytes {
      return moerr.NewInvalidInput(ctx, "MongoDB BSON document exceeds max-value-bytes")
      }
      doc := bson.Raw(raw)
      if err := doc.Validate(); err != nil {
      return moerr.NewInvalidInput(ctx, "MongoDB returned invalid BSON")
      }
      startRows := bat.RowCount()
      committed := false
      defer func() {
      if !committed {
      for _, vec := range bat.Vecs {
      vec.SetLength(startRows)
      }
      bat.SetRowCount(startRows)
      }
      }()
      for i, column := range c.columns {
      value, found, lookupErr := lookupScalarPath(doc, column.Path)
      if !found || lookupErr == nil && (value.Type == bson.TypeNull || value.Type == bson.TypeUndefined) {
      if column.NotNullable {
      return mongoDBNotNullError(ctx, column)
      }
      if appendErr := vector.AppendNull(bat.Vecs[i], mp); appendErr != nil {
      return appendErr
      }
      continue
      }
      if column.Conversion == ConversionTryNull {
      c.conversionAttempts++
      }
      appendErr := lookupErr
      if appendErr == nil {
      appendErr = c.appendValue(bat.Vecs[i], value, column, mp)
      }
      if err := appendErr; err != nil {
      if errors.Is(err, errConversion) && column.Conversion == ConversionTryNull {
      c.conversionErrors++
      metric.MongoDBConversionErrorCounter.Inc()
      if column.NotNullable {
      return mongoDBNotNullError(ctx, column)
      }
      if c.conversionErrors > c.maxConversionErrors ||
      c.conversionAttempts >= conversionErrorRateMinAttempts &&
      float64(c.conversionErrors)/float64(c.conversionAttempts) > c.maxConversionErrorRate {
      return moerr.NewInvalidInput(ctx, "MongoDB try_null conversion error limit exceeded")
      }
      if appendErr := vector.AppendNull(bat.Vecs[i], mp); appendErr != nil {
      return appendErr
      }
      continue
      }
      if errors.Is(err, errConversion) {
      return moerr.NewInvalidInputf(ctx, "MongoDB value at path %s cannot be converted to %s", column.Path, types.T(column.TypeID).String())
      }
      return err
      }
      }
      bat.SetRowCount(startRows + 1)
      committed = true
      return nil
    • mapping.Columns = make([]ColumnMapping, 0, len(columnDefs))
      for i, column := range columnDefs {
      planned := plannedColumns[i]
      if !strings.EqualFold(column.Name.ColName(), planned.Name) {
      return TableMappingSpec{}, moerr.NewInternalError(ctx, "MongoDB parsed and planned column order diverged")
      }
      path := planned.Name
      conversion := mapping.Conversion
      seenPath := false
      seenConversion := false
      for _, attribute := range column.Attributes {
      switch typed := attribute.(type) {
      case *tree.AttributeMongoDBPath:
      if seenPath {
      return TableMappingSpec{}, moerr.NewInvalidInputf(ctx, "duplicate MONGODB_PATH for column %s", planned.Name)
      }
      seenPath = true
      path = typed.Path
      case *tree.AttributeMongoDBConvert:
      if seenConversion {
      return TableMappingSpec{}, moerr.NewInvalidInputf(ctx, "duplicate MONGODB_CONVERT for column %s", planned.Name)
      }
      seenConversion = true
      conversion = strings.ToLower(strings.TrimSpace(typed.Mode))
      }
      }
      if conversion != ConversionStrict && conversion != ConversionTryNull {
      return TableMappingSpec{}, moerr.NewInvalidInputf(ctx, "invalid MONGODB_CONVERT for column %s", planned.Name)
      }
      if err := ValidateBSONPath(ctx, path); err != nil {
      return TableMappingSpec{}, err
      }
      notNullable := planned.Typ.NotNullable
      // CREATE TABLE records declared nullability in Default.NullAbility,
      // while resolved catalog TableDefs also expose it on Typ.NotNullable.
      // Honor both representations so the mapping cannot weaken the schema.
      if planned.Default != nil && !planned.Default.NullAbility {
      notNullable = true
      }
      mapping.Columns = append(mapping.Columns, ColumnMapping{
      Name: planned.Name,
      Path: path,
      TypeID: planned.Typ.Id,
      Width: planned.Typ.Width,
      Scale: planned.Typ.Scale,
      NotNullable: notNullable,
      Conversion: conversion,
      })
  • Snapshot/PITR restore can create orphan MongoDB mappings.

    Bulk restore skips external tables, but mo_mongodb_tables is not in the
    mo_catalog restore skip policy. Restore can therefore clone a historical
    mapping row whose external table and table ID were not restored. The
    orphan dependency then prevents DROP MONGODB CONNECTION, leaving a
    successful restore with unmanageable catalog state. PITR follows the same
    path.

    References:

    • needSkipTablesInMocatalog = map[string]int8{
      "mo_database": 1,
      "mo_tables": 1,
      "mo_columns": 1,
      "mo_table_partitions": 1,
      "mo_foreign_keys": 1,
      "mo_indexes": 1,
      "mo_account": 1,
      catalog.MOVersionTable: 1,
      catalog.MOUpgradeTable: 1,
      catalog.MOUpgradeTenantTable: 1,
      catalog.MOAutoIncrTable: 1,
      "mo_user": 0,
      "mo_role": 0,
      "mo_user_grant": 0,
      "mo_role_grant": 0,
      "mo_role_privs": 0,
      "mo_role_rule": 0,
      "mo_user_defined_function": 0,
      "mo_stored_procedure": 0,
      "mo_mysql_compatibility_mode": 1,
      "mo_stages": 0,
      catalog.MO_PUBS: 1,
      catalog.MO_SUBS: 1,
      catalog.MO_ISCP_LOG: 1,
      catalog.MO_CCPR_LOG: 1,
      catalog.MO_CCPR_TABLES: 1,
      catalog.MO_CCPR_DBS: 1,
      "mo_sessions": 1,
      "mo_configurations": 1,
      "mo_locks": 1,
      "mo_variables": 1,
      "mo_transactions": 1,
      "mo_cache": 1,
      catalog.MO_SNAPSHOTS: 1,
      catalog.MO_PITR: 1,
      catalog.MOPartitionMetadata: 1,
      catalog.MOPartitionTables: 1,
      }
    • for _, tblInfo := range tableInfos {
      key := genKey(dbName, tblInfo.tblName)
      // skip table which is foreign key related
      if _, ok := fkTableMap[key]; ok {
      continue
      }
      // external table data is stored outside MO and cannot be restored by clone.
      if shouldSkipRestoreTableInBulk(tblInfo) {
      if restoreToTbl {
      return newExternalTableRestoreError(ctx, tblInfo, "snapshot")
      }
      getLogger(sid).Debug(fmt.Sprintf("[%s] skip restore external table: %v.%v", snapshotName, tblInfo.dbName, tblInfo.tblName))
      continue
      }
    • for _, tblInfo := range tableInfos {
      if needSkipSystemTable(toAccountId, tblInfo) {
      // TODO skip tables which should not to be restored
      getLogger(sid).Debug(fmt.Sprintf("[%s] skip restore system table: %v.%v, table type: %v", snapshotName, moCatalog, tblInfo.tblName, tblInfo.typ))
      continue
      }
      getLogger(sid).Debug(fmt.Sprintf("[%s] start to restore system table: %v.%v", snapshotName, moCatalog, tblInfo.tblName))
      tblInfo.createSql, err = getCreateTableSql(ctx, bh, tempSnap, dbName, tblInfo.tblName)
      if err != nil {
      return err
      }
      // checks if the given context has been canceled.
      if err = CancelCheck(ctx); err != nil {
      return
      }
      if err = recreateTable(ctx, sid, bh, snapshotName, tblInfo, toAccountId, snapshotTs); err != nil {
      return
      }
    • matrixone/pkg/frontend/pitr.go

      Lines 1442 to 1457 in cf6dca3

      for _, tblInfo := range tableInfos {
      key := genKey(dbName, tblInfo.tblName)
      // skip table which is foreign key related
      if _, ok := fkTableMap[key]; ok {
      continue
      }
      // external table data is stored outside MO and cannot be restored by clone.
      if shouldSkipRestoreTableInBulk(tblInfo) {
      if restoreToTbl {
      return newExternalTableRestoreError(ctx, tblInfo, "pitr")
      }
      getLogger(sid).Info(fmt.Sprintf("[%s] skip restore external table: %v.%v", pitrName, tblInfo.dbName, tblInfo.tblName))
      continue
      }
  • max_by varlen compaction can regress to
    O(winners * chunk_groups).

    Every winner runs compaction checks for all state vectors. Once varlen area
    capacity exceeds 1 MiB, each check scans the whole state vector, up to 8192
    groups, even when compaction is not needed. The existing compaction test has
    one group and does not exercise the multi-group complexity.

    Reference:

    func (exec *maxByExec) copyWinner(dst []*vector.Vector, dstRow int, src []*vector.Vector, srcRows [3]int) error {
    // Reserve every fallible varlen allocation before mutating any of the three
    // correlated state vectors. Without this preflight, an OOM after copying the
    // value but before copying order/tie would publish a mixed winner. Growing
    // capacity is harmless if a later reservation fails; the logical state stays
    // byte-for-byte unchanged and remains safe to serialize or free.
    for i := range dst {
    if src[i].IsNull(uint64(srcRows[i])) || !dst[i].GetType().IsVarlen() {
    continue
    }
    valueBytes := len(src[i].GetRawBytesAt(srcRows[i]))
    if valueBytes <= types.VarlenaInlineSize {
    continue
    }
    if err := dst[i].PreExtendWithArea(0, valueBytes, exec.mp); err != nil {
    return err
    }
    }
    for i := range dst {
    if src[i].IsNull(uint64(srcRows[i])) {
    dst[i].SetNull(uint64(dstRow))
    continue
    }
    if err := dst[i].SetRawBytesAt(dstRow, src[i].GetRawBytesAt(srcRows[i]), exec.mp); err != nil {
    return err
    }
    dst[i].UnsetNull(uint64(dstRow))
    }
    for _, vec := range dst {
    // Compaction is an optional bound on stale varlen area. A failed compact
    // clone leaves the valid original untouched, so memory pressure must not
    // turn a fully copied winner into an aggregate error with ambiguous state.
    _ = compactMaxByStateVector(vec, exec.mp)
    }
    return nil
    }
    func compactMaxByStateVector(vec *vector.Vector, mp *mpool.MPool) error {
    if vec == nil || !vec.GetType().IsVarlen() {
    return nil
    }
    fixedCapacity := vec.Capacity() * vec.GetType().TypeSize()
    areaCapacity := vec.Allocated() - fixedCapacity
    if areaCapacity <= maxByVarlenaCompactionSlack {
    return nil
    }
    liveBytes := 0
    for row := 0; row < vec.Length(); row++ {
    if vec.IsNull(uint64(row)) {
    continue
    }
    valueBytes := len(vec.GetRawBytesAt(row))
    if valueBytes > types.VarlenaInlineSize {
    liveBytes += valueBytes
    }
    }
    if areaCapacity <= 2*liveBytes+maxByVarlenaCompactionSlack {
    return nil
    }

Secondary hardening

  • Add per-key singleflight to cold client acquisition to avoid duplicate
    validation, TLS/SCRAM, Connect, and Ping work.
  • Move best-effort post-commit client retirement to a bounded asynchronous
    queue. Local cleanup can wait up to 10 seconds and remote fanout up to 3
    seconds; cluster restore repeats this serially per account.
  • Remove the MongoDB E2E free_port TOCTOU. Both selected ports are
    released immediately, and the MO port is not bound until after a complete
    build. An adjacent-allocation experiment reused the same port twice in
    20,000 pairs.

Required fix properties

  1. Use a typed, trusted MongoDB catalog discriminator; reject marker injection
    from generic external metadata and add a non-admin E2E test.
  2. Disable temporal comparison/IN pushdown below millisecond scale unless a
    proven preimage-range translation is implemented.
  3. Validate temporal range before arithmetic; apply strict/try-null semantics
    consistently and normalize TIMESTAMP to its declared scale.
  4. Enforce a decoded/vector byte budget during conversion.
  5. Define an explicit restore policy: either skip historical mapping rows or
    recreate external tables and regenerate mappings with restored table IDs.
  6. Track max_by live/stale varlen bytes incrementally and benchmark many groups
    with repeated winners.

Verification already performed

  • Diagnostic red tests reproduced the five authorization/correctness/memory
    failures above; the temporary files were removed afterward.
  • Existing pkg/sql/mongodb, pkg/sql/colexec/mongoscan, and targeted
    max_by tests pass under -race.
  • PR required CI, including MongoDB E2E, UT, SCA, and required BVT, passed.
    Upgrade compatibility jobs were skipped by the workflow.

Related: #26424

Activity

  1. added
    kind/bug
    on Jul 31, 2026
  2. added
    severity/s0
    and removed on Jul 31, 2026
  3. added 5 commits that reference this issue on Jul 31, 2026
    d70ae08
    b812d3d
    7bd138a
    cab39c2
    1280c67
  4. added a commit that references this issue on Aug 3, 2026
    6e506e9
  5. added
    ai-easy
    on Aug 4, 2026
  6. ghost closed this as completedon Aug 5, 2026
  7. added 3 commits that reference this issue on Sep 17, 2026
    a5ec1ca
    df0fe0e
    55dc1c4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ai-easykind/bugphase/testingseverity/s0

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions