Skip to content

Prepare native protobuf records for indexing - #1442

Merged
jwils merged 12 commits into
mainfrom
joshuaw/proto-record-conversion
Nov 29, 2026
Merged

jwils merged 12 commits into
mainfrom
joshuaw/proto-record-conversion

Conversation

@jwils

@jwils jwils commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Why

The indexer needs datastore hashes, but protobuf publishers produce native messages. Converting them into public record hashes first adds a full traversal and extra allocations.

What

Prepare native protobuf messages directly into datastore records in one pass using the generated protobuf runtime metadata and google-protobuf descriptors.

How

ProtoIngestion::RecordPreparer caches field plans built from protobuf descriptors. Sparse runtime metadata supplies field-name overrides, enum names, and scalar types. Renamed built-in scalars retain their indexing preparers, and enum symbols and numbers map consistently across Ruby runtimes.

The preparer applies shared scalar rules, unwraps abstract oneof records, prepares message scalars such as google.protobuf.Timestamp from their canonical protobuf JSON form through the scalar's indexing preparer, and parses and canonicalizes Untyped leaves. The shared indexing pipeline adds __counts afterward.

Preserves field presence, explicit defaults, exact 64-bit integers, nested lists, and concrete types in a single pass.

Risk

Adds ProtoIngestion::RecordPreparer and RuntimeMetadata::Schema.from_schema_artifacts, which become active when #1450 registers the protobuf ingestion adapter. Runtime dependencies are elasticgraph-indexer and google-protobuf.

Testing

No manual testing. Covered by integration specs in record_preparer_spec.rb and unit specs in runtime_metadata/schema_spec.rb.

Bigger picture

Builds on #1441's protobuf publishing test support. Native record validation, adapter registration, and activation of the shared indexing parity suite follow in #1450.

@jwils
jwils added this pull request to stack #1443 October 29, 2026 15:53
@jwils jwils changed the title Convert protobuf records for indexing Prepare native protobuf records for indexing Oct 29, 2026
@jwils
jwils force-pushed the joshuaw/proto-record-conversion branch from 7ec74bf to 7fb2796 Compare November 2, 2026 00:07
@jwils
jwils force-pushed the joshuaw/proto-record-conversion branch 2 times, most recently from 2af56fe to 11abf6f Compare November 5, 2026 20:08
@jwils
jwils force-pushed the joshuaw/proto-record-conversion branch from 11abf6f to bda3128 Compare November 9, 2026 15:58
Base automatically changed from joshuaw/proto-indexing-parity to main November 9, 2026 16:29
jwils added a commit that referenced this pull request Nov 9, 2026
## Why

The shared indexer specs need real protobuf publishers before they can
exercise protobuf ingestion. Their protobuf round trip is still a
placeholder.

## What

Add a test publisher that compiles `schema.proto`, encodes event
batches, and decodes native protobuf records. Extract the shared
`protoc` locator from the existing schema test helper.

## How

The publisher walks protobuf descriptors and uses the generated runtime
metadata for scalar and enum overrides. Each instance owns its
descriptor pool, so tests can encode with an older publisher and decode
with the current schema.

Focused specs cover proto2 and proto3, field presence, nested lists and
abstract types, exact 64-bit integers, timestamps, and disk-backed
artifacts. The publisher stays independent of the production record
preparer.

## Risk

Adds test support and declares runtime dependencies on
`elasticgraph-indexer` and `google-protobuf`. Protobuf ingestion remains
inactive; existing indexing examples stay pending.

## Testing

No manual testing.

## Bigger picture

This prepares the shared indexer parity suite for real protobuf
publishing. Record preparation (#1442) and adapter integration plus
parity-test activation (#1450) follow in this stack.
@jwils
jwils force-pushed the joshuaw/proto-record-conversion branch from 9d326d9 to bcddf29 Compare November 9, 2026 16:29
@jwils
jwils marked this pull request as ready for review November 10, 2026 13:16
@jwils
jwils force-pushed the joshuaw/proto-record-conversion branch from bbd2bb8 to b145edc Compare November 21, 2026 23:24
@myronmarston myronmarston self-assigned this Nov 23, 2026
jwils added a commit that referenced this pull request Nov 24, 2026
Follow-up to
#1442 (comment).

Two caches on the JSON ingestion path memoize into a `Hash.new { |h, k|
h[k] = ... }` default block without synchronization. On JRuby,
concurrent writes to a hash like that can lose entries. The race test in
the linked comment saw the wrong cache size in 193 of 200 runs on JRuby
10.0.2 and 0 of 200 on CRuby 4.0.0.

- `Support::JSONSchema::ValidatorFactory#validator_for`
(`@validators_by_type_name`)
- `JSONIngestion::EnvelopeValidator#validator`
(`@validator_factories_by_version`)

Each cache is now a plain hash, initialized in the constructor and
filled under a `Mutex` with `||=`. This matches how #1442's proto
`RecordPreparer` caches its types. The envelope validator also used to
create its cache hash lazily with `||=`, which was a second race; the
hash is now created in `initialize`. The factory-building logic moved
into a private `build_validator_factory` method, with no change in
behavior.

Testing:
- `script/run_gem_specs elasticgraph-support` and `script/run_gem_specs
elasticgraph-json_ingestion` pass with 100% line and branch coverage.
- `script/type_check` and `standardrb` on the changed files are clean.

Signed-off-by: Josh Wilson <joshuaw@squareup.com>
jwils added a commit that referenced this pull request Nov 25, 2026
…xerExtension

- Eagerly resolve nested `RecordValidator` type plans while holding `@mutex` once per root record, moving validation onto polymorphic `Type#error_for`, `AbstractType#error_for`, and `Field#error_for` (marked `@private` for YARD)
- Drop the empty `Data.define` block on `Descriptors::UnwrappedField` and mark it `@private`
- Lazily require `ingestion_adapter` inside `IndexerExtension#ingestion_adapters_by_format` so referencing `IndexerExtension.name` from `RuntimeMetadata::Schema` and `SchemaDefinition::ResultsExtension` does not cause a circular require or load the indexer at schema-definition time

Co-authored-by: Neon <f833053fa3445a7878359a1bd17c4f6b4ed1ceb3e7414f306f4929b1f9032d02@buzz>
Signed-off-by: Josh Wilson <joshuaw@squareup.com>

@myronmarston myronmarston left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I found some improvements to make on top of this but thought it was easier to just suggest them via a PR that targets this one--that's #1472. I'd also like to replace the mutex with ThreadSafeCache as suggested below.

LGTM otherwise.

jwils and others added 11 commits November 29, 2026 08:51
Keep scalar metadata when built-in names are customized. Accept numeric enum values from JRuby and avoid native message singleton mocks. Include a reproducible preparation benchmark.
Only format google.protobuf.Timestamp using DateTime directly; prepare other external message scalars (such as google.protobuf.Duration) via JSON encoding and the scalar's indexing preparer.

Co-authored-by: Josh Wilson <joshuaw@squareup.com>
Signed-off-by: Josh Wilson <joshuaw@squareup.com>
Test one observable behavior per example and assert on the whole prepared record. Drop the mocks and class patches that pinned internal caching and hash conversion, and freeze native records so every example verifies preparation does not mutate them. Define each syntax's schema once per context.

Co-authored-by: Josh Wilson <joshuaw@squareup.com>
Signed-off-by: Josh Wilson <joshuaw@squareup.com>
Protobuf metadata is appended after any user-registered indexer extension, so a lookup that picked the first extension would pass every other spec.

Co-authored-by: Josh Wilson <joshuaw@squareup.com>
Signed-off-by: Josh Wilson <joshuaw@squareup.com>
Preparation output does not depend on proto2 versus proto3, so the specs use the default syntax once. Records are never nil and unknown enum numbers are rejected before preparation, so drop those fallbacks and cover the reachable nested empty abstract wrapper instead. Move `Schema.from_schema_artifacts` coverage into its own spec.

Co-authored-by: Josh Wilson <joshuaw@squareup.com>
Signed-off-by: Josh Wilson <joshuaw@squareup.com>
Drop the `google.protobuf.Timestamp` special case so every message scalar is prepared from its canonical protobuf JSON form by its scalar's indexing preparer.

Co-authored-by: Josh Wilson <joshuaw@squareup.com>
Signed-off-by: Josh Wilson <joshuaw@squareup.com>
- Drop empty `Data.define` blocks on `RecordPreparer::Type` and `Field`
- Reference `IndexerExtension.name` instead of duplicating the class name string
- Move the `google_protobuf.rbs` comment directly above `def subtype`
- Add specs covering renaming a non-default scalar to its wire default name and `__typename` on lists of abstract objects under `name_in_index`

Co-authored-by: Neon <f833053fa3445a7878359a1bd17c4f6b4ed1ceb3e7414f306f4929b1f9032d02@buzz>
Signed-off-by: Josh Wilson <joshuaw@squareup.com>
…o Type, AbstractType, and Field

Resolve nested message types and abstract `oneof` alternatives up front while holding `@mutex` once per root record, memoizing shared nested types in `@types`. Move per-type preparation onto `Type#prepare` and `AbstractType#prepare` (removing nilable `Type#fields`) and per-field preparation onto `Field#prepare_into` so nested messages and list elements prepare directly without re-acquiring `@mutex`.

Co-authored-by: Neon <f833053fa3445a7878359a1bd17c4f6b4ed1ceb3e7414f306f4929b1f9032d02@buzz>
Signed-off-by: Josh Wilson <joshuaw@squareup.com>
YARD does not inherit `@private` from `RecordPreparer` onto nested `Data.define` classes, which caused `site:docs_coverage` to flag `Type#prepare` and `AbstractType#prepare` as undocumented public methods.

Co-authored-by: Neon <f833053fa3445a7878359a1bd17c4f6b4ed1ceb3e7414f306f4929b1f9032d02@buzz>
Signed-off-by: Josh Wilson <joshuaw@squareup.com>
Replace the explicit `@mutex` and plain `@types`/`@enums` hashes with `Support::ThreadSafeCache` now that #1470 is on `main`, keeping reentrant nested type resolution and making `@enums` explicitly thread-safe.

Co-authored-by: Neo <f833053fa3445a7878359a1bd17c4f6b4ed1ceb3e7414f306f4929b1f9032d02@buzz>
Signed-off-by: Josh Wilson <joshuaw@squareup.com>
@jwils
jwils force-pushed the joshuaw/proto-record-conversion branch from 71db773 to e58a6b4 Compare November 29, 2026 14:53
@jwils
jwils merged commit 2684bc8 into main Nov 29, 2026
24 checks passed
@jwils
jwils deleted the joshuaw/proto-record-conversion branch November 29, 2026 15:23
jwils added a commit that referenced this pull request Nov 29, 2026
…xerExtension

- Eagerly resolve nested `RecordValidator` type plans while holding `@mutex` once per root record, moving validation onto polymorphic `Type#error_for`, `AbstractType#error_for`, and `Field#error_for` (marked `@private` for YARD)
- Drop the empty `Data.define` block on `Descriptors::UnwrappedField` and mark it `@private`
- Lazily require `ingestion_adapter` inside `IndexerExtension#ingestion_adapters_by_format` so referencing `IndexerExtension.name` from `RuntimeMetadata::Schema` and `SchemaDefinition::ResultsExtension` does not cause a circular require or load the indexer at schema-definition time

Co-authored-by: Neon <f833053fa3445a7878359a1bd17c4f6b4ed1ceb3e7414f306f4929b1f9032d02@buzz>
Signed-off-by: Josh Wilson <joshuaw@squareup.com>
jwils added a commit that referenced this pull request Nov 29, 2026
Apply the #1442 review feedback that moved `RecordPreparer` off its
mutex to `RecordValidator` too. `Support::ThreadSafeCache` takes a
reentrant `Monitor`, so `build_type` can still resolve nested types
through the same cache while the lock is held once per root record.

Co-authored-by: Executor1 <7c44932696c451281ba60b1d7e7d4ff253bb8a7f11e58ae1e8e3a5945334567c@sprout-oss.stage.blox.sqprod.co>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Josh Wilson <joshuaw@squareup.com>
Signed-off-by: Josh Wilson <joshuaw@squareup.com>
myronmarston added a commit that referenced this pull request Nov 30, 2026
…es, imported message zero values (#1472)

## Summary

Follow-ups to `RecordPreparer` from #1442, proposed as a stacked PR.

```diff
 build_scalar_preparer
+  Timestamp field whose scalar uses the DateTime preparer
+    Time.at(seconds, nanos, :nsec).iso8601(DATE_TIME_PRECISION)
   other message scalar
-    preparer(JSON.parse(encode_json(value)))
+    preparer(JSON.parse(encode_json(value, emit_defaults: true)))

 build_enum
-  {symbol => name, number => name}
+  {symbol => name}

 schema generator and RecordPreparer
-  "value", "values", zero value name minus "_UNSPECIFIED"
+  ProtoConversions::ABSTRACT_TYPE_ONEOF_NAME, LIST_WRAPPER_VALUES_FIELD_NAME, enum_value_prefix(name)
```

- **Timestamps:** most of the cost per `Timestamp` was
`IndexingPreparers::DateTime` re-parsing an ISO 8601 string. The direct
format gives the same output: it truncates to milliseconds and handles
negative `seconds`.
- **Imported message scalars:** the canonical protobuf JSON form omits
zero-valued fields. For example, a `geo_point` scalar with `lat: 0` was
indexed as `{"lon" => 5.5}`.
- **Enum numbers:** decoded messages return known enum values as symbols
on MRI and on JRuby. Only a JRuby `RepeatedField#push(0)` keeps a
number, and only the spec did that.
- **Shared names:** the generator and `RecordPreparer` now use the same
constants for the names that the generator emits. `ProtoPublisher` keeps
its own derivation, so it stays an independent check.

## Evidence

- **Before:** the new imported-message spec failed: `expected
{"location" => {"lat" => 0.0, "lon" => 5.5}}, got {"location" => {"lon"
=> 5.5}}`.
  **After:** it passes.
- No existing spec failed under these broken implementations. Each now
fails a new spec:
  - The `Timestamp` shortcut ignores the scalar's preparer.
- The shortcut rounds instead of truncating, or computes with a `Float`.
  - Treat every message outside `google.protobuf` as an object type.
  - List recursion drops the nested mapping below the first list level.
  - Presence methods use snake_case names.
  - A field named `value` marks a type as abstract.
- **Benchmark:** for one `Timestamp` value on MRI 4.0, preparation takes
2.0 µs on the JSON path and 0.4 µs on the direct format.

## Merge Danger

**Door:** two-way

**Blast Radius:** `elasticgraph-proto_ingestion`. The only effect
outside it is a new optional `proto_paths:` argument on
`SpecSupport::ProtoPublisher`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
jwils added a commit that referenced this pull request Nov 30, 2026
…xerExtension

- Eagerly resolve nested `RecordValidator` type plans while holding `@mutex` once per root record, moving validation onto polymorphic `Type#error_for`, `AbstractType#error_for`, and `Field#error_for` (marked `@private` for YARD)
- Drop the empty `Data.define` block on `Descriptors::UnwrappedField` and mark it `@private`
- Lazily require `ingestion_adapter` inside `IndexerExtension#ingestion_adapters_by_format` so referencing `IndexerExtension.name` from `RuntimeMetadata::Schema` and `SchemaDefinition::ResultsExtension` does not cause a circular require or load the indexer at schema-definition time

Co-authored-by: Neon <f833053fa3445a7878359a1bd17c4f6b4ed1ceb3e7414f306f4929b1f9032d02@buzz>
Signed-off-by: Josh Wilson <joshuaw@squareup.com>
jwils added a commit that referenced this pull request Nov 30, 2026
Apply the #1442 review feedback that moved `RecordPreparer` off its
mutex to `RecordValidator` too. `Support::ThreadSafeCache` takes a
reentrant `Monitor`, so `build_type` can still resolve nested types
through the same cache while the lock is held once per root record.

Co-authored-by: Executor1 <7c44932696c451281ba60b1d7e7d4ff253bb8a7f11e58ae1e8e3a5945334567c@sprout-oss.stage.blox.sqprod.co>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Josh Wilson <joshuaw@squareup.com>
Signed-off-by: Josh Wilson <joshuaw@squareup.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants