Skip to content

feat: monthly active records (MAR) metering pipeline - #7119

Merged
am6010 merged 61 commits into
masterfrom
feature/pro-5774-mar-rudder-server-gate-meter-hll-strip-flush
Jul 3, 2026
Merged

am6010 merged 61 commits into
masterfrom
feature/pro-5774-mar-rudder-server-gate-meter-hll-strip-flush

Conversation

@am6010

@am6010 am6010 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Description

Adds the Monthly Active Records (MAR) metering pipeline to rudder-server, modeled on the existing MTU / tracked-users flow. The feature meters activation records per destination, aggregates them in-app using HyperLogLog, and flushes them through the reporting pipeline.

Key changes:

  • Reporter core (enterprise/activationrecords/): MAR reporter, factory, and noop implementation with gating and HLL settings.
  • Flusher pipeline (enterprise/reporting/flusher/): ActivationRecordsInAppAggregator with destination-keyed HLL aggregation, wired into the flusher factory and mediator runner.
  • Processor hook (processor/): meters MAR activation records during pre-transform and strips context.activation before storing in the txn store.
  • App wiring (app/): registers the MAR feature and wires both the embedded and processor app handlers.
  • Migration: adds the activation_records_reports table.
  • Tests: reporter grain/gate/HLL tests, dest-keyed aggregation integration test, end-to-end wire-compat consumer test, and processor strip assertions.

Review fixes (B1/B2/B3)

Two independent code reviews flagged three blocking issues, now fixed:

  • B1 — context.activation leaked to destinations. The strip mutated the raw job.EventPayload bytes, but destination-bound events are separately-parsed singularEvent maps. Fixed by stripping context.activation per-event in preprocessStage (covers the transformer input, eventsByMessageID, and the archival payloadFunc), unconditionally. The redundant raw-bytes strip is removed. A new processor test captures the destination-bound transformer input and asserts context.activation is absent on every event of a multi-event batch.
  • B2 — only batch[0] was metered/stripped. A job batch can hold multiple events; the meter now iterates the full batch array (every event metered exactly once), and the per-event strip naturally covers all events.
  • B3 — client-controlled origin could abort the store transaction. The origin column is widened from VARCHAR(64) to TEXT, length-capped defensively, and the MAR write is now best-effort: wrapped in a Postgres SAVEPOINT so a failed COPY rolls back only the MAR insert (logging + activation_records_store_error stat) instead of failing event delivery.

Linear Ticket

https://linear.app/rudderstack/issue/PRO-5774

Security

  • The code changed/added as part of this pull request won't create any security issues with how the software is being used.
  • Fixes a data-leak where an internal metering namespace (context.activation) could reach destination payloads.

am6010 added 22 commits June 22, 2026 17:21
Bootstrap the knowledge base for cloning the tracked-users (MTU)
reporting pipeline into MAR (Monthly Active Records) with three deltas
(gate, key, query). Documents the reporter, processor hook sites,
gateway rETL source/destination params, the flusher/aggregator/client
flush path, feature + app-handler wiring, and migration embedding.
Records the HLL wire-compat contract and fail-closed gate as traps.

🔒 Scanned for secrets using gitleaks 8.28.0
Clone of the tracked-users pipeline for Monthly Active Records (MAR):
- UniqueActivationRecordsReporter builds per-(workspace,source,destination)
  HLL sketches from the stamped context.activation fingerprint
- HLL params (Log2m=16, Regwidth=5, AutoExplicitThreshold, SparseEnabled)
  and murmur seed 123 reuse the tracked-users wire contract verbatim
- fail-closed gate: jobs missing fingerprint or origin are skipped (stat)
- config-gated factory returns a noop reporter when ActivationRecords.enabled
  is false (default)
- MigrateDatabase migrates the activation_records dir into
  activation_records_reports_migrations

🔒 Scanned for secrets using gitleaks 8.28.0
Docker-free table-driven tests for GenerateReportsFromJobs covering the
grain (workspace,source,destination), the fail-closed fingerprint/origin
gate, duplicate-fingerprint cardinality, multi-destination fan-out, and
the wire-compat HLL defaults (Log2m=16, Regwidth=5).

🔒 Scanned for secrets using gitleaks 8.28.0
New migration set auto-embedded via the recursive go:embed glob; the
grain columns (source_id, destination_id, origin) are NOT NULL since the
fail-closed gate guarantees them.

🔒 Scanned for secrets using gitleaks 8.28.0
…-meter-hll-strip-flush

🔒 Scanned for secrets using gitleaks 8.28.0
…st-keyed HLL aggregation

🔒 Scanned for secrets using gitleaks 8.28.0
… branch, and mediator runner

🔒 Scanned for secrets using gitleaks 8.28.0
…dating dest-keyed aggregation

🔒 Scanned for secrets using gitleaks 8.28.0
…ate-meter-hll-strip-flush

🔒 Scanned for secrets using gitleaks 8.28.0
…e txn

Wire the activation-records (MAR) reporter alongside the existing tracked-users
(MTU) reporter: a processor-local activationRecordsReporter interface, Handle
field + Setup wiring, manager New/Start pass-through, generate at the
pre-transform stage with no source filter, and report inside the same
WithUpdateSafeTx store transaction. Immediately after generate, strip
batch[0].context.activation from each job payload via go-kit jsonparser.DeleteKey
so the internal metering fields never reach the destination (no-op when absent).
The MTU calls are left unchanged.

🔒 Scanned for secrets using gitleaks 8.28.0
Add the ActivationRecords feature interface and factory registration in the app,
and Setup+MigrateDatabase(activation_records)+inject the reporter into proc.New in
BOTH processorAppHandler and embeddedAppHandler, mirroring TrackedUsers. Wiring
both handlers ensures MAR meters in both deployment topologies.

🔒 Scanned for secrets using gitleaks 8.28.0
…on strip

Pass activationrecords.NewNoopActivationRecordsReporter() at every Handle.Setup and
manager New call site so the suite compiles with the new dependency, inject it at the
trackedUsers mock-injection sites, and assert that a record job's payload no longer
carries batch[0].context.activation after the pre-transform stage — proving the strip
runs before transformation.

🔒 Scanned for secrets using gitleaks 8.28.0
…e-meter-hll-strip-flush

🔒 Scanned for secrets using gitleaks 8.28.0
Prove the READ/CONSUMER side of the MAR wire contract. The gate is
fail-closed, so a write->read mismatch undercounts silently at runtime
and must be locked by tests:
- jsonparser read-path over the exact gateway SingularEventBatch shape
- connection-grain derivation (source/destination/origin)
- HLL byte round-trip under Log2m=16/Regwidth=5 via hll.FromBytes
- fail-closed proofs: missing fingerprint/origin/destination_id => 0

🔒 Scanned for secrets using gitleaks 8.28.0
…ver-gate-meter-hll-strip-flush

🔒 Scanned for secrets using gitleaks 8.28.0
The CreateRunner guard still reported 'Only tracked_users_reports is
supported now' after activation_records_reports was added to
supportedTables; align it with the trailing guard's message.

🔒 Scanned for secrets using gitleaks 8.28.0
…ment

🔒 Scanned for secrets using gitleaks 8.28.0
unparam (golangci-lint, new:false in CI) flagged test helpers whose
sourceID/origin args always received the same literal. Inline the
constants so the helpers expose only the axes the tests vary.

🔒 Scanned for secrets using gitleaks 8.28.0
…-gate-meter-hll-strip-flush

🔒 Scanned for secrets using gitleaks 8.28.0
Synthesises all stage memories (reporter-core, flusher-pipeline,
processor-hook, wire-compat-and-tests, integration-verify) into the
loom knowledge base:

- architecture.md: MAR as implemented sibling of MTU — per-file breakdown,
  diff table (gate/key/route/columns), wiring confirmation in both handlers.
- entry-points.md: all new MAR files with key symbols and line anchors.
- patterns.md: end-to-end 11-step clone recipe (MAR as worked example);
  origin-is-carried-not-keyed rationale.
- mistakes.md: 6 new prevention rules — unparam one-at-a-time scan,
  sandbox golangci-lint, processor dockertest timeout, jsonparser bracket
  notation, three-struct carrier chain, signature ripple to test call sites,
  package-level name conflicts.
- concerns.md: mark supportedTables concern resolved; add loom acceptance
  timeout vs dockertest integration suites.

🔒 Scanned for secrets using gitleaks 8.28.0
…gate-meter-hll-strip-flush

🔒 Scanned for secrets using gitleaks 8.28.0
🔒 Scanned for secrets using gitleaks 8.28.0
@codecov

codecov Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 73.57860% with 79 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.60%. Comparing base (421c613) to head (e0740ef).
⚠️ Report is 5 commits behind head on master.

Files with missing lines Patch % Lines
enterprise/activationrecords/records_reporter.go 72.32% 28 Missing and 16 partials ⚠️
...ing/flusher/aggregator/activation_records_inapp.go 71.42% 8 Missing and 8 partials ⚠️
app/apphandlers/processorAppHandler.go 0.00% 7 Missing ⚠️
app/apphandlers/embeddedAppHandler.go 42.85% 2 Missing and 2 partials ⚠️
enterprise/reporting/flusher/factory.go 75.00% 2 Missing and 1 partial ⚠️
enterprise/reporting/mediator.go 40.00% 2 Missing and 1 partial ⚠️
processor/processor.go 91.30% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #7119      +/-   ##
==========================================
- Coverage   79.66%   79.60%   -0.07%     
==========================================
  Files         584      592       +8     
  Lines       65483    65912     +429     
==========================================
+ Hits        52167    52469     +302     
- Misses      10253    10341      +88     
- Partials     3063     3102      +39     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@am6010 am6010 changed the title feat: Monthly Active Records (MAR) metering pipeline feat: monthly active records (MAR) metering pipeline Jun 24, 2026
am6010 added 6 commits June 24, 2026 18:04
… best-effort

Strip context.activation unconditionally from each parsed batch event in
preprocessStage so it never reaches a destination, removing the redundant
raw-bytes strip in pretransformStage. Wrap the MAR (activation records)
write in a Postgres SAVEPOINT so a failed COPY rolls back only the MAR
insert instead of poisoning the gateway-status transaction and dropping
event delivery; failures log and increment activation_records_store_error.

🔒 Scanned for secrets using gitleaks 8.28.0
Inspect the destination-bound transformer input via
WithDynamicDestinationTransform and assert context.activation is absent on
every event, including a multi-event batch (batch[0] and batch[1]).

🔒 Scanned for secrets using gitleaks 8.28.0
Iterate the whole batch array when aggregating activation records so every
event is metered exactly once (previously only batch[0]), preserving the
fail-closed skip for events missing fingerprint/origin. Defensively cap
origin to 256 runes with a rune-safe truncation.

🔒 Scanned for secrets using gitleaks 8.28.0
Assert the grain HLL cardinality reflects all unique fingerprints across a
multi-event batch, and that a valid element is still metered when a sibling
element is skipped.

🔒 Scanned for secrets using gitleaks 8.28.0
origin can exceed 64 chars; widen the brand-new column from VARCHAR(64) to
TEXT. COPY column order is unchanged.

🔒 Scanned for secrets using gitleaks 8.28.0
Comment thread processor/processor.go Resolved
am6010 added 6 commits June 30, 2026 14:26
preprocessStage runs for every source type, not just rETL, and context is a
customer-extensible object. Unconditionally deleting context.activation could
clobber a customer-set field. Strip only the fingerprint we stamp for MAR
metering, and drop the activation namespace only when it is left empty.

🔒 Scanned for secrets using gitleaks 8.28.0
message-3 carries only our fingerprint (whole namespace removed); message-4
carries a customer field alongside it (fingerprint stripped, field preserved).

🔒 Scanned for secrets using gitleaks 8.28.0
Classify MAR-eligible jobs by source_category (gateway-stamped from
SourceDefinition.Category) and skip anything that is not the reverse-ETL
"warehouse" category. This stops a client from being metered by stamping
context.activation.fingerprint on a non-rETL (e.g. event-stream) source,
rather than relying on the fingerprint gate alone. Non-rETL is the expected
majority of traffic, so it is skipped silently with no per-job skip stat.

🔒 Scanned for secrets using gitleaks 8.28.0
Assert a non-rETL source carrying a client-injected fingerprint is skipped,
and stamp source_category=warehouse into the reporter, wire-compat, and
end-to-end fixtures so rETL records are metered.

🔒 Scanned for secrets using gitleaks 8.28.0
The router only delivers warehouse-source (reverse-ETL) jobs when a top-level
connection exists for the source/destination pair (router/worker.go). The MAR
e2e now sets the source category to warehouse, so it must also register the
connection, mirroring a real rETL setup. Adds ConfigBuilder.WithConnection and
wires it into the test so all events reach the destination again.

🔒 Scanned for secrets using gitleaks 8.28.0
@am6010
am6010 requested review from itsmihir and mihir20 July 1, 2026 07:04
am6010 added 5 commits July 1, 2026 17:45
Restore origin as a carried (non-keyed) column end-to-end: the reporter reads
context.activation.origin, defensively 256-rune-truncates it (emitting
activation_records_origin_truncated), and fails closed on missing origin; it
is written in the COPY and read back in the aggregator SELECT/Scan and shipped
on the ActivationRecordsReport wire payload.

Reverses the earlier origin removal while keeping the source_category=warehouse
metering gate intact.

🔒 Scanned for secrets using gitleaks 8.28.0
Re-add origin TEXT NOT NULL to the activation_records_reports init schema
(edited 000001 in place; it has not shipped to any environment).

🔒 Scanned for secrets using gitleaks 8.28.0
Re-add origin to the reporter unit/wire-compat helpers and assertions, the
flusher integration report + payload expectations, and the e2e grain/rETL
structs (including the AND origin filter in countActivationRecords). Restore
the "missing origin - skip" case.

🔒 Scanned for secrets using gitleaks 8.28.0
Only reverse-ETL (warehouse) sources stamp context.activation for MAR metering,
so the destination-bound strip is now gated on the source's
SourceDefinition.Category: a customer-set context.activation on any other source
type is left untouched.

On rETL sources the strip now also removes context.activation.origin (previously
only fingerprint was removed), so the internal metering origin no longer leaks to
destinations; any other keys under context.activation are preserved as customer
data. The per-event strip is extracted into stripActivationMetadata.

The existing end-to-end trackedUsers spec uses a webhook (non-rETL) source, so
its assertions now verify context.activation is preserved untouched.

🔒 Scanned for secrets using gitleaks 8.28.0
Table-driven coverage for stripActivationMetadata: reverse-ETL events have
fingerprint and origin removed (the activation namespace dropped when left empty,
customer fields kept), while non-reverse-ETL events are left fully intact by the
source-category gate.

🔒 Scanned for secrets using gitleaks 8.28.0
Comment thread processor/processor.go Resolved

@itsmihir itsmihir left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

lets rename flusher/aggregator/types.go -> flusher/aggregator/tracked_users_types.go

am6010 added 4 commits July 2, 2026 10:17
…rce_id

Event-stream jobs are the expected majority and are skipped by the
reverse-ETL source_category gate anyway, so check the category first to
avoid the source_id parse on every non-rETL job.

🔒 Scanned for secrets using gitleaks 8.28.0
…adata

Move the isReverseETLSource check to the call site so the helper takes a
single argument and does one job. Test mirrors the caller's gate so the
non-rETL cases still verify customer context.activation is preserved.

🔒 Scanned for secrets using gitleaks 8.28.0
HLL settings are validated once at startup, so NewHll cannot fail on the
hot path with the same settings. A failure would be deterministic across
the whole batch, so the previous skip+stat would silently under-count MAR
billing data while reporting success. Panic to fail loud and let the batch
retry, consistent with the panic in trackedusers' users_reporter.

🔒 Scanned for secrets using gitleaks 8.28.0
Names the file after the TrackedUsersReport type it holds, matching the
sibling activation_records_types.go in the same package.

🔒 Scanned for secrets using gitleaks 8.28.0

@mihir20 mihir20 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

we can also update pipeline test here. Otherwise LGTM

am6010 added 2 commits July 3, 2026 10:36
🔒 Scanned for secrets using gitleaks 8.28.0
…ition worker pipeline

🔒 Scanned for secrets using gitleaks 8.28.0
@am6010
am6010 merged commit d1df486 into master Jul 3, 2026
126 of 130 checks passed
@am6010
am6010 deleted the feature/pro-5774-mar-rudder-server-gate-meter-hll-strip-flush branch July 3, 2026 08:37
This was referenced Jul 6, 2026
itsmihir pushed a commit that referenced this pull request Jul 6, 2026
🤖 I have created a release *beep* *boop*
---


##
[1.80.0-rc.1](v1.79.0...v1.80.0-rc.1)
(2026-07-06)


### Features

* add control-plane connection management for processor
([#7126](#7126))
([ea6ca00](ea6ca00))
* carry integration version on DestinationT to the transformer
([#7125](#7125))
([421c613](421c613))
* implement Forward RPC for control-plane requests to workspace pyt
transformers
([#7143](#7143))
([8a704cf](8a704cf))
* implement Kubernetes deployment scaler for workspace replica
management
([#7123](#7123))
([84fc747](84fc747))
* monthly active records (MAR) metering pipeline
([#7119](#7119))
([d1df486](d1df486))


### Bug Fixes

* **router:** transformer returning response with empty metadata array
causes server to panic
([#7144](#7144))
([d6a4dbc](d6a4dbc))


### Miscellaneous

* enable compression for google pubsub
([#7137](#7137))
([11c9ab8](11c9ab8))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: rudderstack-github-actions[bot] <236995729+rudderstack-github-actions[bot]@users.noreply.github.com>
itsmihir pushed a commit that referenced this pull request Jul 7, 2026
🤖 I have created a release *beep* *boop*
---


##
[1.80.0](v1.79.0...v1.80.0)
(2026-07-06)


### Features

* add control-plane connection management for processor
([#7126](#7126))
([ea6ca00](ea6ca00))
* carry integration version on DestinationT to the transformer
([#7125](#7125))
([421c613](421c613))
* implement Forward RPC for control-plane requests to workspace pyt
transformers
([#7143](#7143))
([8a704cf](8a704cf))
* implement Kubernetes deployment scaler for workspace replica
management
([#7123](#7123))
([84fc747](84fc747))
* monthly active records (MAR) metering pipeline
([#7119](#7119))
([d1df486](d1df486))


### Bug Fixes

* **router:** transformer returning response with empty metadata array
causes server to panic
([#7144](#7144))
([d6a4dbc](d6a4dbc))


### Miscellaneous

* enable compression for google pubsub
([#7137](#7137))
([11c9ab8](11c9ab8))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: rudderstack-github-actions[bot] <236995729+rudderstack-github-actions[bot]@users.noreply.github.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.

3 participants