bleak.Data.Transformer 2.2.0

dotnet add package bleak.Data.Transformer --version 2.2.0
                    
NuGet\Install-Package bleak.Data.Transformer -Version 2.2.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="bleak.Data.Transformer" Version="2.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="bleak.Data.Transformer" Version="2.2.0" />
                    
Directory.Packages.props
<PackageReference Include="bleak.Data.Transformer" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add bleak.Data.Transformer --version 2.2.0
                    
#r "nuget: bleak.Data.Transformer, 2.2.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package bleak.Data.Transformer@2.2.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=bleak.Data.Transformer&version=2.2.0
                    
Install as a Cake Addin
#tool nuget:?package=bleak.Data.Transformer&version=2.2.0
                    
Install as a Cake Tool

bleak.Data.Transformer

A config-driven ETL engine. You describe — in a single JSON file — which files to read, how to type their columns, how to join/nest them, what transforms to apply, and where to write the result. The engine then Extracts the sources, Transforms each row through per-field pipelines, and Loads the output as JSONL.

It is designed for large inputs: sources are read with a fully streaming reader, and joins can run with bounded memory via disk-backed external sort + merge.

All examples below use a small invented dataset (customers / orders / line items). Substitute your own files and columns.


Table of contents

  1. Installation
  2. Concepts
  3. The input files
  4. Quick start
  5. Running the engine
  6. The config file, section by section
  7. Worked examples
  8. Output format
  9. Join strategies
  10. Error handling
  11. Type reference
  12. Logging
  13. Extending the engine
  14. Troubleshooting

The terse schema reference is ETL-CONFIG.md.


Installation

dotnet add package bleak.Data.Transformer --version 2.2.0
<PackageReference Include="bleak.Data.Transformer" Version="2.2.0" />

Concepts

                ┌─────────── one JSON config ───────────┐
  files  ──▶    │  sources (aliased, typed)             │
               │       │                                │
               │       ▼                                │
               │  outputs[]  ── relationships (nesting) │
               │       │       fields → transform pipes │
               │       ▼                                │
  JSONL  ◀──    │  load (split into N-record files)     │
                └────────────────────────────────────────┘
  • Source — one input file, given an alias. Columns can be typed (string, integer, decimal, …).
  • Output — one feed produced from the sources. It is a tree of nodes: a primary source plus nested child sources joined on a key (to any depth).
  • Field — one property in the output. It starts from a source column, optionally runs through a transform pipeline, and is emitted as its declared type.
  • Transform — a step that converts/formats/computes a value. Steps chain: each step's output is the next step's input.

Input fields are typed but never transformed; transforms live only on output fields.


The input files

The engine reads delimited text files (CSV, TSV, pipe, semicolon, or any single-character delimiter). A header row is expected by default. Example files for this guide:

customers.csv

customer_id,first_name,last_name,email,signup_date,lifetime_value
1001,Ada,Lovelace,ada@example.com,2021-03-15,2540.50
1002,Alan,Turing,alan@example.com,2020-11-02,180.00
1003,Grace,Hopper,grace@example.com,2022-07-21,

orders.tsv (tab-separated)

order_id	customer_id	order_date	subtotal	discount
9001	1001	2023-01-10	100.00	10.00
9002	1001	2023-02-14	50.00	0
9003	1002	2023-03-01	200.00	25.00

line_items.csv

order_id,sku,quantity,unit_price
9001,WIDGET-A,2,30.00
9001,WIDGET-B,1,40.00
9002,WIDGET-A,5,10.00
9003,GADGET-Z,1,200.00

Quick start

The smallest useful config: read one file, type a few columns, write JSONL.

etl.quickstart.etlconfig

{
  "version": 1,
  "sources": {
    "customers": {
      "file": "customers.csv",
      "fields": {
        "customer_id":    { "type": "integer" },
        "signup_date":    { "type": "date", "format": "yyyy-MM-dd" },
        "lifetime_value": { "type": "decimal" }
      }
    }
  },
  "outputs": [
    {
      "name": "customers",
      "mode": "object",
      "source": "customers",
      "fields": [
        { "name": "id",            "from": "customer_id",    "type": "integer" },
        { "name": "email",         "from": "email",          "type": "string"  },
        { "name": "joined",        "from": "signup_date",    "type": "date"    },
        { "name": "lifetime_value","from": "lifetime_value", "type": "decimal" }
      ],
      "load": { "fileBaseName": "customers", "splitEvery": 1000000 }
    }
  ]
}

Output (one JSON object per line; note 1003's empty lifetime_value is omitted):

{"id":1001,"email":"ada@example.com","joined":"2021-03-15","lifetime_value":2540.50}
{"id":1002,"email":"alan@example.com","joined":"2020-11-02","lifetime_value":180.00}
{"id":1003,"email":"grace@example.com","joined":"2022-07-21"}

Running the engine

Option A — the console command

In DataMonger, choose “Extract / Transform / Load (config-driven)”. It then:

  1. lists the bundled .etlconfig files (from data/etlconfig) with a number each — pick one by number, or type the path to your own .etlconfig file; then
  2. prompts for the output folder — unless every output sets its own load.folder, in which case there's no prompt.

Everything else (input files, split size, join strategy, error policy) comes from the config. Source file paths in the config are resolved relative to the config file's own folder (absolute paths are also accepted). Config files use the .etlconfig extension but are JSON (jsonc — comments and trailing commas allowed).

Option B — programmatically

using bleak.Data.Transformer.Config;
using bleak.Data.Transformer.Engine;
using Microsoft.Extensions.Logging;

// Any Microsoft.Extensions.Logging provider works; this one needs the Microsoft.Extensions.Logging.Console package.
using var loggerFactory = LoggerFactory.Create(b => b.AddConsole().SetMinimumLevel(LogLevel.Information));

var configPath = "/path/to/etl.quickstart.etlconfig";
var config     = EtlConfigLoader.FromFile(configPath);
var configDir  = Path.GetDirectoryName(Path.GetFullPath(configPath))!;  // base for relative file paths
var timestamp  = DateTime.Now.ToString("yyyyMMdd_HHmmss");

IReadOnlyList<EtlOutputResult> results =
    EtlEngine.Run(config, configDir, outputFolder: "/path/to/out", timestamp, loggerFactory);

foreach (var r in results)
    Console.WriteLine($"{r.Name}: {r.Records:N0} records, {r.Files.Count} file(s), {r.Rejected:N0} skipped");

EtlConfigLoader accepts JSON with comments and trailing commas (jsonc), so your config can be annotated. Each EtlOutputResult reports Name, Records, Files (final paths), Rejected, Filtered, Warnings and Bytes. The loggerFactory argument is optional; see Logging.

Run options (machine-level tuning)

How many threads to use, how much memory the sorts may take and where they spill depend on the machine, not on the data, so they are not part of the .etlconfig. Pass an EtlRunOptions as the last argument (null means EtlRunOptions.Default):

var options = new EtlRunOptions
{
    MaxDegreeOfParallelism = 0,           // 0 = Environment.ProcessorCount; 1 = everything on the calling thread
    SortMemoryBudgetBytes  = 4L << 30,    // shared by the external sorts running at the same time
    SortChunkSize          = 200_000,     // max records per sort chunk
    TempDirectory          = null,        // spill folder; null = system temp
    // Optimization switches, all on by default (see "How externalMerge runs" below):
    ShareScans = true, PruneColumns = true, PushDownFilters = true, StreamNestedJoins = true,
    CleanupStaleTempDirectories = true,
};
EtlEngine.Run(config, configDir, outputFolder, timestamp, loggerFactory, options);

The engine takes the options as a plain parameter and has no dependency on a DI container. In a Generic Host app, bind them from configuration and inject IOptions<EtlRunOptions> where you call the engine:

services.AddOptions<EtlRunOptions>().BindConfiguration("Etl");

EtlRunOptions.Sequential turns off threads and every sharing/pushdown optimization (useful to rule them out while debugging); tests check that it writes byte-identical files to the default options.


The config file, section by section

Top-level shape:

{
  "version": 1,
  "run":     { /* run-wide settings */ },
  "sources": { /* alias -> source */ },
  "outputs": [ /* one entry per feed */ ]
}

run

field values default meaning
joinStrategy hashInMemory · externalMerge hashInMemory How relationships are joined. See Join strategies.
onError skip · abort · nullify skip What to do when a row hits a fatal transform error. See Error handling.
emitEmpty true · false false false omits empty-string fields; true keeps them, emitting "" (e.g. a blank middle_name). Null values and empty arrays are always omitted.
"run": { "joinStrategy": "externalMerge", "onError": "skip" }

sources

A map of alias → source. The alias is how outputs and relationships refer to the file.

"sources": {
  "customers": {
    "file": "customers.csv",   // relative to the config file (absolute allowed)
    "format": "delimited",     // "delimited" today; "json"/"xml" reserved
    "delimiter": "csv",        // see table below
    "quote": "\"",             // text qualifier
    "hasHeader": true,         // first row is the header
    "fields": {                // OPTIONAL input typing; unlisted columns stay strings
      "customer_id":    { "type": "integer" },
      "signup_date":    { "type": "date", "format": "yyyy-MM-dd", "culture": "en-US" },
      "lifetime_value": { "type": "decimal" }
    }
  },
  "orders":     { "file": "orders.tsv", "delimiter": "tsv",
                  "fields": { "order_id": { "type": "integer" }, "customer_id": { "type": "integer" },
                              "subtotal": { "type": "decimal" }, "discount": { "type": "decimal" } } },
  "line_items": { "file": "line_items.csv",
                  "fields": { "order_id": { "type": "integer" }, "quantity": { "type": "integer" },
                              "unit_price": { "type": "decimal" } } }
}

Delimiter values (shorthand or a literal character):

value delimiter
csv · comma · , comma
tsv · tab · \t tab
pipe · \| pipe
semicolon · ; semicolon
any single character that character

Input field typing. Each entry under fields declares a column's type so the value is parsed once on read. date/datetime may add a format (a .NET format string; ISO-8601 is assumed if omitted) and a culture (invariant if omitted). Empty cells become null. Input fields carry no transforms.

outputs

Each output is the root node of a tree: source + fields + optional children, plus a mode and a load block. There are two modes.

mode: "object" — one JSON object per primary row
{
  "name": "customer_orders",
  "mode": "object",
  "source": "customers",
  "fields":   [ /* ...root fields... */ ],
  "children": [ /* ...nested relationships... */ ],
  "load":     { "fileBaseName": "customer_orders", "splitEvery": 1000000 }
}
mode: "keyedMap" — one object per group, keyed by a dynamic expression
{
  "name": "emails_by_customer",
  "mode": "keyedMap",
  "source": "customers",
  "groupBy": "customer_id",
  "keyExpr": { "pipeline": [ { "op": "concat", "values": [ { "literal": "email::" }, { "field": "email" } ] } ] },
  "dedup":   { "within": "email", "keepMaxOf": "signup_date" },   // optional; default: no dedup
  "fields":  [ /* ...the value object for each key... */ ],
  "load":    { "fileBaseName": "emails_by_customer", "splitEvery": 1000000 }
}

keyedMap groups the primary source by groupBy, then for each row emits a property whose name is the keyExpr pipeline result and whose value is the mapped fields object. dedup is optional: within each group it keeps, per distinct within value, the row with the greatest keepMaxOf (string/ISO-date comparison).

Fields & types

{ "name": "joined", "from": "signup_date", "type": "date", "pipeline": [ /* optional steps */ ] }
key meaning
name the output JSON property name
from source column the pipeline starts from. May be omitted for fully computed fields (the pipeline then starts from null).
type the emitted JSON type — string, integer, decimal, double, bool, date, datetime, plus object (object-group) and array
pipeline optional ordered list of transform steps

The pipeline result is coerced to type before writing. Null or empty values are omitted from the output object (an empty array is omitted too). date emits yyyy-MM-dd; datetime emits ISO-8601.

Output field order is the order you list fields — properties are emitted in fields order, then the node's relationships. Reorder fields to reorder the JSON. To place an array-of-objects between scalar fields, use an inline relationship field (below).

Inline relationship fields (array of objects, positioned)

A field with a source renders as an array of objects right where you list it (its fields describe each element). distinctBy keeps the first element per distinct value of a column; limit caps the count. Any relationship (inline or in children) accepts distinctBy/limit.

{ "name": "client_ids", "type": "array",
  "source": "emails", "on": { "parent": "id", "child": "person_id" },
  "distinctBy": "email_key", "limit": 1,
  "fields": [
    { "name": "name",  "type": "string", "pipeline": [ { "op": "concat", "values": [ { "literal": "ext_id" } ] } ] },
    { "name": "value", "from": "addr", "type": "string" }
  ] }
// -> "client_ids": [ { "name": "ext_id", "value": "ada@example.com" } ]
Object-group fields (type: "object")

Emit a nested object built from the same row: its own fields, and optionally relationships in children (joined against the current row, rendered inside the group). Object-groups nest.

{ "name": "address", "type": "object",
  "fields": [
    { "name": "city",  "from": "city",  "type": "string" },
    { "name": "state", "from": "state", "type": "string" }
  ],
  "children": [
    { "source": "shipments", "as": "shipments", "cardinality": "many",
      "on": { "parent": "address_id", "child": "address_id" },
      "fields": [ { "name": "tracking", "from": "tracking", "type": "string" } ] }
  ] }
Lookup fields

Pull a value from a related source (joined on a key) rather than the current row — for values that don't live on the primary row. The engine builds an in-memory index over the lookup source.

// single scalar: the first match (coerced to the field's type)
{ "name": "region", "type": "string",
  "lookup": { "source": "stores", "on": { "parent": "store_id", "child": "id" },
              "column": "region", "single": true } }

// array of values: distinct, optionally capped (limit:1 = "first available")
{ "name": "channel_ids", "type": "array",
  "lookup": { "source": "orders", "on": { "parent": "customer_id", "child": "customer_id" },
              "column": "channel_id", "distinct": true } }
lookup key meaning
source source alias to read from
on.parent / on.child join: column on the current row / column on the lookup source
column the lookup source column to project
single true → first match as a scalar; false → an array of matches
distinct array only: drop duplicates (first-seen order)
limit array only: cap the count (1 = first available)

Relationships (nesting)

A children entry joins another source to its parent and nests the result. Children may have their own children, to any depth.

"children": [
  {
    "source": "orders",            // child source alias
    "as": "orders",                // JSON property to nest under
    "cardinality": "many",         // "many" -> array; "one" -> single object
    "on": { "parent": "customer_id", "child": "customer_id" },
    "fields": [ /* order fields */ ],
    "children": [
      {
        "source": "line_items",
        "as": "items",
        "cardinality": "many",
        "on": { "parent": "order_id", "child": "order_id" },
        "fields": [ /* line-item fields */ ]
      }
    ]
  }
]
  • on.parent is a column on the parent node's source; on.child is a column on the child's source.
  • Composite (multi-column) joins: use on.parents / on.children (positionally matched) to match on more than one column — e.g. match a customer's per-brand rows on both keys: "on": { "parents": ["customer_key","brand"], "children": ["customer_key","brand"] }. Supported by hashInMemory (and below the top level under externalMerge).
  • cardinality: "one" nests a single object (omitted entirely if there is no match); "many" nests an array (empty [] when there are no matches).

Combining sources into one array (shared as). Two or more child relationships with the same as are concatenated into a single array (declaration order). This puts heterogeneous rows in one list — e.g. email rows and phone rows under one contacts array:

"children": [
  { "source": "emails", "as": "contacts", "cardinality": "many", "on": { "parent": "id", "child": "person_id" },
    "fields": [ { "name": "type", "type": "string", "pipeline": [ { "op": "concat", "values": [ { "literal": "email" } ] } ] },
                { "name": "value", "from": "addr", "type": "string" } ] },
  { "source": "phones", "as": "contacts", "cardinality": "many", "on": { "parent": "id", "child": "person_id" },
    "fields": [ { "name": "type", "type": "string", "pipeline": [ { "op": "concat", "values": [ { "literal": "phone" } ] } ] },
                { "name": "value", "from": "number", "type": "string" } ] }
]

Transform pipeline

Steps run top to bottom. Each step receives the running value (the previous step's output, or the field's from value for the first step) and returns the next running value. Operations that need more than one input (arithmetic, concat) name extra operands explicitly.

An operand is exactly one of:

{ "field": "discount" }     // the typed value of a column on the current row
{ "literal": 1.1 }          // a constant (string / number / bool)
{ "value": true }           // the current running value

Operation catalog:

op params effect
toString culture? convert running value → string
toInteger (alias toInt) — → 64-bit integer
toDecimal — → decimal (exact)
toDouble — → double (floating)
toBool — → bool (true/false, also 1/0)
toDate format?, culture? parse → date
toDateTime format?, culture? parse → datetime
dateFormat format (required), culture? format a date/datetime → string
numberFormat format (required), culture? format a number → string (e.g. "N2", "F2", "C", "P1")
add subtract multiply divide rhs (operand) runningValue <op> rhs
concat values (operands), separator? join operands into a string
split separator? (default ;) split a string into an array of strings (trimmed, empties dropped); use type: "array"
lower / upper — lowercase / uppercase the running string

Arithmetic computes in decimal unless either operand is a double/float, in which case it computes in double.

Per-step error handling with onError:

{ "op": "toInteger", "onError": "throw" }            // default — raise a row-level error
{ "op": "toInteger", "onError": "null" }             // quietly become null
{ "op": "toInteger", "onError": { "default": 0 } }   // substitute a value

A thrown row-level error is then handled by the run's onError policy.

load

"load": { "format": "jsonl", "folder": "~/Desktop", "fileBaseName": "customer_orders", "splitEvery": 1000000 }
field default meaning
format jsonl output format (JSONL today; the writer is pluggable)
folder (prompted) output folder for this feed. Supports ~ and paths relative to the config file. When omitted, the command prompts for one (and that prompt is skipped entirely if every output sets a folder).
fileBaseName output base of the output file name
splitEvery 1000000 start a new file every N records

Files are written as {fileBaseName}_{timestamp}.jsonl, or {fileBaseName}_{timestamp}_{n}.jsonl when the record count exceeds splitEvery.

Paths — source file paths and load.folder both support a leading ~ (home directory) and resolve relative to the config file's folder when not absolute.

filter — drop records before they're written

An output may declare a filter: a list of conditions the primary record must satisfy (all, ANDed) to be emitted. Records that fail are excluded and counted (FilteredCount on the output's completed log event). Set filterExcludedFile: true to also append the excluded rows to {fileBaseName}_{timestamp}_filtered.csv.

"filter": [
  { "column": "order_datetime", "op": "onOrAfter", "value": "now-2years" }
],
"filterExcludedFile": false
op meaning
onOrAfter after onOrBefore before date compare; value is an ISO date or a relative token (now, now-2years, now-90days, now-12hours). A missing/unparseable date fails the condition.
eq ne gt ge lt le compare (numeric if both parse as numbers, else ordinal string)
in value is an array; the column must be one of them
empty / notEmpty the column is/ isn't blank

Relative tokens resolve to run start time, so now-2years ages records out as the clock advances.


Worked examples

Example A — flat output with a computed field

Compute net_total = (subtotal − discount) and a formatted display string, from orders.tsv.

{
  "version": 1,
  "sources": {
    "orders": {
      "file": "orders.tsv", "delimiter": "tsv",
      "fields": {
        "order_id":    { "type": "integer" },
        "customer_id": { "type": "integer" },
        "order_date":  { "type": "date", "format": "yyyy-MM-dd" },
        "subtotal":    { "type": "decimal" },
        "discount":    { "type": "decimal" }
      }
    }
  },
  "outputs": [
    {
      "name": "orders", "mode": "object", "source": "orders",
      "fields": [
        { "name": "order_id",    "from": "order_id",    "type": "integer" },
        { "name": "customer_id", "from": "customer_id", "type": "integer" },

        // start from subtotal, subtract the discount column -> net total
        { "name": "net_total", "from": "subtotal", "type": "decimal",
          "pipeline": [ { "op": "subtract", "rhs": { "field": "discount" } } ] },

        // a human-readable string built from the net total (computed again, then formatted)
        { "name": "net_display", "from": "subtotal", "type": "string",
          "pipeline": [
            { "op": "subtract",     "rhs": { "field": "discount" } },
            { "op": "numberFormat", "format": "C2", "culture": "en-US" }
          ] },

        // reformat the date into a different string layout
        { "name": "ordered_on", "from": "order_date", "type": "string",
          "pipeline": [ { "op": "dateFormat", "format": "MMM d, yyyy", "culture": "en-US" } ] }
      ],
      "load": { "fileBaseName": "orders", "splitEvery": 1000000 }
    }
  ]
}

Result:

{"order_id":9001,"customer_id":1001,"net_total":90.00,"net_display":"$90.00","ordered_on":"Jan 10, 2023"}
{"order_id":9002,"customer_id":1001,"net_total":50.00,"net_display":"$50.00","ordered_on":"Feb 14, 2023"}
{"order_id":9003,"customer_id":1002,"net_total":175.00,"net_display":"$175.00","ordered_on":"Mar 1, 2023"}

Example B — nested object, two levels deep

Customers → their orders → each order's line items.

{
  "version": 1,
  "run": { "joinStrategy": "externalMerge", "onError": "skip" },
  "sources": {
    "customers":  { "file": "customers.csv",  "fields": { "customer_id": { "type": "integer" }, "lifetime_value": { "type": "decimal" } } },
    "orders":     { "file": "orders.tsv", "delimiter": "tsv",
                    "fields": { "order_id": { "type": "integer" }, "customer_id": { "type": "integer" },
                                "subtotal": { "type": "decimal" }, "discount": { "type": "decimal" } } },
    "line_items": { "file": "line_items.csv",
                    "fields": { "order_id": { "type": "integer" }, "quantity": { "type": "integer" }, "unit_price": { "type": "decimal" } } }
  },
  "outputs": [
    {
      "name": "customer_orders", "mode": "object", "source": "customers",
      "fields": [
        { "name": "customer_id",    "from": "customer_id",    "type": "integer" },
        { "name": "name",           "type": "string",
          "pipeline": [ { "op": "concat", "separator": " ",
                          "values": [ { "field": "first_name" }, { "field": "last_name" } ] } ] },
        { "name": "email",          "from": "email",          "type": "string"  },
        { "name": "lifetime_value", "from": "lifetime_value", "type": "decimal" }
      ],
      "children": [
        {
          "source": "orders", "as": "orders", "cardinality": "many",
          "on": { "parent": "customer_id", "child": "customer_id" },
          "fields": [
            { "name": "order_id",  "from": "order_id",  "type": "integer" },
            { "name": "net_total", "from": "subtotal",  "type": "decimal",
              "pipeline": [ { "op": "subtract", "rhs": { "field": "discount" } } ] }
          ],
          "children": [
            {
              "source": "line_items", "as": "items", "cardinality": "many",
              "on": { "parent": "order_id", "child": "order_id" },
              "fields": [
                { "name": "sku",      "from": "sku",        "type": "string"  },
                { "name": "quantity", "from": "quantity",   "type": "integer" },
                // line total = quantity * unit_price
                { "name": "line_total", "from": "quantity", "type": "decimal",
                  "pipeline": [ { "op": "toDecimal" }, { "op": "multiply", "rhs": { "field": "unit_price" } } ] }
              ]
            }
          ]
        }
      ],
      "load": { "fileBaseName": "customer_orders", "splitEvery": 500000 }
    }
  ]
}

Result for customer 1001 (pretty-printed for readability — actual output is one line per record):

{
  "customer_id": 1001,
  "name": "Ada Lovelace",
  "email": "ada@example.com",
  "lifetime_value": 2540.50,
  "orders": [
    { "order_id": 9001, "net_total": 90.00, "items": [
        { "sku": "WIDGET-A", "quantity": 2, "line_total": 60.00 },
        { "sku": "WIDGET-B", "quantity": 1, "line_total": 40.00 } ] },
    { "order_id": 9002, "net_total": 50.00, "items": [
        { "sku": "WIDGET-A", "quantity": 5, "line_total": 50.00 } ] }
  ]
}

Note: name has no from — it is built purely from a concat of two other columns. line_total starts from quantity, converts it to decimal, then multiplies by the unit_price operand.

Example C — keyedMap with dedup

Build, per customer, a map keyed by email::<address>, keeping only the most recent record per address.

{
  "version": 1,
  "sources": {
    "customers": { "file": "customers.csv",
                   "fields": { "customer_id": { "type": "integer" }, "signup_date": { "type": "date", "format": "yyyy-MM-dd" } } }
  },
  "outputs": [
    {
      "name": "emails_by_customer", "mode": "keyedMap", "source": "customers",
      "groupBy": "customer_id",
      "keyExpr": { "pipeline": [ { "op": "concat", "values": [ { "literal": "email::" }, { "field": "email" } ] } ] },
      "dedup":   { "within": "email", "keepMaxOf": "signup_date" },
      "fields": [
        { "name": "value",       "from": "email",       "type": "string" },
        { "name": "customer_id", "from": "customer_id", "type": "integer" },
        { "name": "first_name",  "from": "first_name",  "type": "string" }
      ],
      "load": { "fileBaseName": "emails_by_customer", "splitEvery": 1000000 }
    }
  ]
}

Result (one object per customer group):

{"email::ada@example.com":{"value":"ada@example.com","customer_id":1001,"first_name":"Ada"}}
{"email::alan@example.com":{"value":"alan@example.com","customer_id":1002,"first_name":"Alan"}}
{"email::grace@example.com":{"value":"grace@example.com","customer_id":1003,"first_name":"Grace"}}

Example D — object-groups, lookups, split, and a shared as

A richer profile: a tags array (split), an object-group ids holding an array lookup, a scalar lookup, and a contacts array that unions email + phone rows, where each email contact wraps its fields in a details object-group with a nested loyalty array.

Input files:

# people.csv
id,name,tags
1,Ada,vip;beta

# emails.csv
person_id,addr,brand,email_key
1,ada@example.com,ACME,EK1
1,ada@example.com,ZENITH,EK1

# phones.csv
person_id,number
1,555-0100

# loyalty.csv
email_key,tier
EK1,GOLD
{
  "version": 1,
  "sources": {
    "people":  { "file": "people.csv",  "fields": { "id": { "type": "integer" } } },
    "emails":  { "file": "emails.csv",   "fields": { "person_id": { "type": "integer" } } },
    "phones":  { "file": "phones.csv",   "fields": { "person_id": { "type": "integer" } } },
    "loyalty": { "file": "loyalty.csv" }
  },
  "outputs": [
    {
      "name": "profiles", "mode": "object", "source": "people",
      "fields": [
        { "name": "id",   "from": "id",   "type": "integer" },
        { "name": "name", "from": "name", "type": "string" },
        { "name": "tags", "from": "tags", "type": "array", "pipeline": [ { "op": "split", "separator": ";" } ] },
        { "name": "ids", "type": "object",
          "fields": [
            { "name": "email_keys", "type": "array",
              "lookup": { "source": "emails", "on": { "parent": "id", "child": "person_id" }, "column": "email_key", "distinct": true } }
          ] },
        { "name": "first_brand", "type": "string",
          "lookup": { "source": "emails", "on": { "parent": "id", "child": "person_id" }, "column": "brand", "single": true } }
      ],
      "children": [
        { "source": "emails", "as": "contacts", "cardinality": "many", "on": { "parent": "id", "child": "person_id" },
          "fields": [
            { "name": "type",  "type": "string", "pipeline": [ { "op": "concat", "values": [ { "literal": "email" } ] } ] },
            { "name": "value", "from": "addr", "type": "string" },
            { "name": "details", "type": "object",
              "fields": [ { "name": "brand", "from": "brand", "type": "string" } ],
              "children": [
                { "source": "loyalty", "as": "loyalty", "cardinality": "many",
                  "on": { "parent": "email_key", "child": "email_key" },
                  "fields": [ { "name": "tier", "from": "tier", "type": "string" } ] }
              ] }
          ] },
        { "source": "phones", "as": "contacts", "cardinality": "many", "on": { "parent": "id", "child": "person_id" },
          "fields": [
            { "name": "type",  "type": "string", "pipeline": [ { "op": "concat", "values": [ { "literal": "phone" } ] } ] },
            { "name": "value", "from": "number", "type": "string" }
          ] }
      ],
      "load": { "fileBaseName": "profiles", "splitEvery": 1000000 }
    }
  ]
}

Result (pretty-printed; actual output is one line):

{
  "id": 1,
  "name": "Ada",
  "tags": ["vip", "beta"],
  "ids": { "email_keys": ["EK1"] },
  "first_brand": "ACME",
  "contacts": [
    { "type": "email", "value": "ada@example.com", "details": { "brand": "ACME",   "loyalty": [ { "tier": "GOLD" } ] } },
    { "type": "email", "value": "ada@example.com", "details": { "brand": "ZENITH", "loyalty": [ { "tier": "GOLD" } ] } },
    { "type": "phone", "value": "555-0100" }
  ]
}

tags is a split array; ids is an object-group wrapping a distinct array lookup; first_brand is a single lookup; contacts unions the emails and phones relationships (shared as); and each email's details is an object-group with a nested loyalty array.


Output format

  • JSONL — one JSON document per line.
  • Null/empty omission — a field whose final value is null or an empty string is left out of the object entirely (it is not written as null). Set run.emitEmpty: true to keep blank strings (emitted as ""); nulls and empty arrays are always omitted.
  • Typing — integer/decimal/double emit JSON numbers, bool emits true/false, date emits "yyyy-MM-dd", datetime emits ISO-8601, everything else emits a JSON string.
  • File splitting — output rolls to a new file every splitEvery records; a single-file run drops the ordinal suffix.
  • Relaxed escaping — characters like @ and + are written literally rather than \uXXXX.

Join strategies

Set once per run via run.joinStrategy.

strategy how it works use when
hashInMemory (default) Streams the primary source row-by-row; loads child/dimension sources into memory indexed by their join key. Handles arbitrary nesting depth. Children/dimensions fit comfortably in RAM. Simple and fast.
externalMerge Disk-backed external sort + merge join of the primary and its direct children in one streaming pass — neither needs to fit in RAM. Very large primary and child files.

Join keys are compared as ordinal strings, so single-column, composite (on.parents/on.children), and non-numeric keys all work under externalMerge.

externalMerge characteristics / limits:

  • All direct children of a node must join on the same parent key column(s) (otherwise use hashInMemory for that output — you'll get a clear error message).
  • A grandchild whose join key starts with its parent's join key (parent on customer_key, grandchild on customer_key, brand) is streamed from a sorted file like the top level, so it need not fit in RAM. Other levels below the top are nested from in-memory indexes (logged at run time), so those sources must fit in RAM.
  • Output is ordered by the join key (the primary is sorted), not source order. The sort is stable (since 2.2), so rows with equal keys keep their file order, and so do the children of each record.
  • A primary row whose join key equals the previous row's key gets no children: the merge cursors have already moved past that key. hashInMemory gives every such row its children. Use distinctBy on the key (and put the row you want first) or hashInMemory if duplicate primary keys need children.
  • Needs scratch space for the sort runs (EtlRunOptions.TempDirectory, default the system temp dir).

How externalMerge runs (2.2):

  • Shared scans. Relations that read the same file on the same key (and case rule) share one read and one sort; when the primary itself is that file on that key, it shares the stream too. Identical in-memory indexes are built once.
  • Output fan-out. Outputs with the same primary file and join tree (same files, keys, case rules and cardinalities at every level) are produced from one join pass. Filters, fields, relation filters and load may all differ: they are applied per output after the join.
  • Pushdown. Columns that appear nowhere in a relation's config are blanked before sorting and indexing, and a many relation's filter is applied before its source is sorted (same output, less to sort). When a stream is shared, a row is kept if any of its relations could use it.
  • Parallelism. All sorts and in-memory indexes of a join are prepared in parallel, every sorted stream merges one batch ahead on a pool thread, lookups are built in parallel, and records are rendered on several threads and written in order by a dedicated writer thread.
  • Memory. Lookup indexes are released once no remaining output uses them. Sort chunks are capped by SortMemoryBudgetBytes as well as by row count.
  • None of this changes the output: tests compare every file against EtlRunOptions.Sequential byte for byte.

Error handling

Two levels work together:

  1. Per-step onError decides what a single transform does on failure: throw (default), null (yield null), or { "default": <value> } (substitute).
  2. Run onError decides what happens when a step throws:
run.onError behavior
skip (default) Drop the offending record, count it (a Warning log event reports the total), and append the raw primary row to {fileBaseName}_{timestamp}_rejects.csv. The run finishes.
abort Stop the whole run immediately with a descriptive error.
nullify Omit only the failing field and keep the record.

Example: parse a quantity strictly, but never let a bad value abort the run — drop those rows and keep a record of them.

"run": { "onError": "skip" },
...
{ "name": "quantity", "from": "quantity", "type": "integer",
  "pipeline": [ { "op": "toInteger", "onError": "throw" } ] }

Type reference

type CLR JSON output parse notes
string string string as-is
integer 64-bit long number long.Parse; decimals/doubles round
decimal decimal number exact; good for money
double double number floating point
bool bool true/false accepts true/false, 1/0
date DateTime "yyyy-MM-dd" format on input; ISO-8601 if omitted
datetime DateTime ISO-8601 (o) format on input; ISO-8601 if omitted
object — nested object an object-group: its own fields + nested children
array — JSON array from a split transform or an array lookup; omitted when empty

All parsing uses the invariant culture unless a culture is supplied on the field/step.


Logging

EtlEngine.Run(..., ILoggerFactory? loggerFactory = null) takes a standard Microsoft.Extensions.Logging factory as its last parameter. null (the default) means no logging. The library references only Microsoft.Extensions.Logging.Abstractions, so plug in whatever provider you use (console, Serilog, OpenTelemetry, ...). All events are source-generated [LoggerMessage] methods with structured properties, so a disabled level costs nothing, and per-record timestamps are only taken when Debug is on.

The factory is handed down to every component, each with its own category:

Category Information Debug Trace
bleak.Data.Transformer.Engine.EtlEngine run started (JobName, outputs, sources); output completed (records, rejected, filtered, warnings, files, bytes, DurationMs, RecordsPerSecond); run completed (totals, DurationMs, RecordsPerSecond); sample / key-filter run notices output started; join strategy chosen and why; per lookup index built (rows, distinct keys); phase finished lines for lookupCache, transform, write, sampling lookup skip reasons; the exception of a failed run
bleak.Data.Transformer.Engine.RecordWriter - per-step transform costs at the end of each output: one line per transform/filter op, plus a summary (see Per-step transform costs) the same costs broken down per field and op
bleak.Data.Transformer.Engine.EtlCompiler - phase compile finished (readers opened, lookups, relations); sample pre-pass; key filter scope key filter values
bleak.Data.Transformer.Join.HashInMemoryJoinStrategy / ExternalMergeJoinStrategy - phase join (or group) finished: primary rows, child rows matched, orphans, DurationMs -
bleak.Data.Transformer.Join.InMemoryNester - in-memory index built per relation (rows, distinct keys) -
bleak.Data.Transformer.Sources.DelimitedSourceReader - source read finished per source (rows, bytes, DurationMs) -
bleak.Data.Transformer.Sources.EncryptedSourceCache - cache hit on disk; miss (decrypt / gunzip ms, bytes); phase encryptedSourceCache finished (hits, misses) in-process cache hit
bleak.Data.Transformer.Output.JsonlSplitWriter - - one line per output file part (records, bytes)
bleak.Data.InfiniteDataLoader.* (CsvReader, ExternalSorter) external sort started / completed reader opened/closed; sort phases per spilled chunk

Warnings: aggregate counts only, per output: rejected records, records with field warnings, lookup rows whose projection failed, run.maxRecords reached, and a sampled source without the key column. The per-row detail stays in the *_rejects.csv / *_warnings.csv / *_filtered.csv files, never in the logs. Error: a run that throws logs RunFailed with the exception type only (the exception itself is rethrown to you and attached to a Trace event), because exception messages can quote a record value.

Every Information "completed" line and every Debug "phase finished" line has DurationMs plus size counters (RecordCount, RowCount, ByteCount, FileCount, ...), so throughput can be computed from the structured properties. Phases run as one stream, so their times overlap: the join phase's DurationMs is the time spent inside the join itself, including reading (and for externalMerge, sorting) its inputs; transform is rendering and filtering, excluding file writes (write) and sampling (sampling). With parallel rendering, transform is the render time summed over the render threads, so it can exceed wall-clock.

2.2 adds: ETL run options (Debug, event 1004); Outputs ... produced from a single join pass (Information, 1018) when outputs are fanned out; Released ... lookup indexes (Debug, 1025); the externalMerge plan line (Debug, 1704) with how many sorted streams served how many relations, whether the primary shared one, nested streams, pushdown and pruned columns; and In-memory join index reused (Debug, 1501).

Per-step transform costs

To see which transform and filter steps cost the most inside an output's transform phase, enable Debug for the bleak.Data.Transformer.Engine.RecordWriter category. You can do that on its own, with the rest at Information:

using var loggerFactory = LoggerFactory.Create(b => b
    .AddConsole()
    .SetMinimumLevel(LogLevel.Information)
    .AddFilter("bleak.Data.Transformer.Engine.RecordWriter", LogLevel.Debug));

At the end of each output, the engine logs these events:

ID Level Event Template
1800 Debug StepCost Transform step {StepName} ({StepKind}) in output {OutputName}: {InvocationCount} invocations, {ErrorCount} errors, {DurationMs} ms. One line per op, sorted by DurationMs descending.
1801 Debug StepSummary Transform steps for output {OutputName}: {StepCount} steps, {InvocationCount} invocations, {ErrorCount} errors, {DurationMs} ms measured in steps of {TransformMs} ms transform phase ({MeasuredPercent}%)
1802 Trace FieldStepCost Transform step {StepName} ({StepKind}) on field {FieldName} in output {OutputName}: ... (same counters). One line per (field, op), sorted by DurationMs descending.
  • StepName is the op as written in the config, such as map, toDate, concat, or a filter op like notEmpty or onOrAfter. Op names are matched case-insensitively, as the registry resolves them, so map and Map are reported on one line. StepKind is transform or filter.
  • Steps measured: field pipelines (including coalesce and lookup post-processing), keyExpr, relation keyBy and mergePrefix, output filter conditions, and relation filter conditions. Lookup expr and lookup filter run while the lookup index is built, so they are part of the lookupCache phase and are not counted here.
  • ErrorCount counts the times a step threw, including throws its onError then turned into null or a default. A filter condition that returns false is not an error.
  • FieldName is the field's dotted path through object groups and relations, such as site_contacts.email. Pseudo-fields name the other places a step can sit: (keyExpr), site_contacts(keyBy), site_contacts(mergePrefix), (filter).email (output filter on column email), and site_contacts(filter).status.
  • TransformMs is the same transform phase time as event 1031. The share not spent in steps (100 - MeasuredPercent) goes to everything else in that phase: reading typed column values, output type coercion, lookups and relation selection, and JSON rendering. Sample re-renders are not counted, because they belong to the sampling phase.
  • Cost. When Debug is off for RecordWriter, the compiler builds the plain steps and filters, so the per-record path is unchanged: no probes, no extra checks and no allocations. When it is on, each step and filter condition is compiled with a timing probe that adds two Stopwatch.GetTimestamp() calls and an array increment per invocation (counters are arrays indexed by a compiled step id). On a 200k-row benchmark with 13 steps (about 2.5 million step invocations), that added about 20% to the run.

Event IDs (unique within this assembly): 1000-1099 EtlEngine, 1100-1199 EtlCompiler, 1200-1299 DelimitedSourceReader, 1300-1399 EncryptedSourceCache, 1400-1499 JsonlSplitWriter, 1500-1599 InMemoryNester, 1600-1699 HashInMemoryJoinStrategy, 1700-1799 ExternalMergeJoinStrategy, 1800-1899 RecordWriter. bleak.Data.InfiniteDataLoader numbers its own events from 1000 too, so filter on category plus ID.

Data guarantee: at Debug and above the engine logs metadata only: counts, byte sizes, durations, file names and paths, config, output, source, field and column names, and transform op names. Field values, keys and record contents never appear at Debug or above. The encrypted source cache never logs the passphrase, key material or gpg output at any level. Trace may include record values (lookup skip reasons, key filter values, exception detail), so keep Trace off for real client data.

Changes in 2.2.0

Performance release; the output of a run is unchanged except where noted.

  • New EtlRunOptions and EtlEngine.Run(..., ILoggerFactory?, EtlRunOptions?) overload (the 2.1 overload still works and uses EtlRunOptions.Default). New ExternalMergeJoinStrategy(EtlRunOptions, ILoggerFactory?) constructor.
  • externalMerge shares scans and sorts, fans out outputs with the same join tree, streams grandchildren whose key starts with the parent's key, pushes many-relation filters and unused columns below the sort, and prepares inputs, builds lookups and renders records in parallel. See How externalMerge runs.
  • Ordering of equal keys. The external sort is now stable (bleak.Data.InfiniteDataLoader 2.1), so records and nested children with equal join keys come out in file order; 2.1 left that order unspecified. Where several rows share a key, this decides which one a one relation or distinctBy keeps (now: the first in the file).
  • All outputs are compiled before the first one runs, so a config error in any output fails the run before anything is written. Readers open their file only when it is read, and each file's header is read once per run.
  • NodePlan.SourceIdentity and NodePlan.UsedColumns, DelimitedSourceReader.FilePath, Delimiter and Quote.
  • Leftover extsort_* folders from killed runs are deleted at the start of an externalMerge run.
  • Dependencies: bleak.Data.InfiniteDataLoader 2.1.0, Microsoft.Extensions.Logging.Abstractions 10.0.14.

Changes in 2.1.0

  • New per-step transform cost events from RecordWriter (1800-1802), described above.
  • RecordWriter takes an optional ILogger<RecordWriter>? logger = null as its last constructor parameter. EtlEngine.Run passes one from its loggerFactory. This is an additive change.
  • The transform phase time (event 1031) no longer subtracts the time spent closing the output files, which happens outside the per-record loop. Before this fix, small runs could report too low a time, even a negative one.
  • Dependencies: bleak.Data.InfiniteDataLoader 2.0.1, Microsoft.Extensions.Logging.Abstractions 10.0.14.

Upgrading from 1.x

2.0.0 replaces the Action<string>? log callbacks with Microsoft.Extensions.Logging and moves to bleak.Data.InfiniteDataLoader 2.0.0:

1.x 2.0
EtlEngine.Run(..., Action<string>? log = null) EtlEngine.Run(..., ILoggerFactory? loggerFactory = null)
new EtlCompiler(..., Action<string>? log = null) new EtlCompiler(..., ILoggerFactory? loggerFactory = null)
new ExternalMergeJoinStrategy(chunkSize, Action<string>? log = null) new ExternalMergeJoinStrategy(chunkSize, ILoggerFactory? loggerFactory = null)
new HashInMemoryJoinStrategy() new HashInMemoryJoinStrategy(ILoggerFactory? loggerFactory = null)
InMemoryNester.ForSubtree(node) InMemoryNester.ForSubtree(node, ILogger<InMemoryNester>? logger = null)
new DelimitedSourceReader(path, delimiter, quote) new DelimitedSourceReader(path, delimiter, quote, string? sourceName = null, ILoggerFactory? loggerFactory = null)
SourceReaderFactory.Open(source, baseDirectory) SourceReaderFactory.Open(source, baseDirectory, string? sourceName = null, ILoggerFactory? loggerFactory = null)
new JsonlOutputWriter(folder, baseName, timestamp, splitEvery) new JsonlOutputWriter(folder, baseName, timestamp, splitEvery, ILoggerFactory? loggerFactory = null)
new JsonlSplitWriter(folder, baseName, timestamp, recordsPerFile) new JsonlSplitWriter(folder, baseName, timestamp, recordsPerFile, ILogger<JsonlSplitWriter>? logger = null)

The old free-text lines (--- output (mode, strategy) ---, lookup reused ..., N record(s) skipped -> path) are now the structured events above. New: EtlConfig.Name ("name" in the config), EtlOutputResult.Bytes, JsonlOutputWriter.BytesWritten / FilesWritten, JsonlSplitWriter.BytesWritten.


Extending the engine

The engine is built around small interfaces so you can grow it without touching the pipeline:

  • Transforms — ITransform implementations are registered by op name in TransformRegistry.CreateDefault(). Add a new op by registering a factory:
    registry.Register("upper", _ => new UpperTransform());   // class UpperTransform : ITransform
    
  • Sources — implement ISourceReader (today: DelimitedSourceReader). This is where JSON/XML sources will plug in; the rest of the pipeline is unaffected.
  • Output — implement IOutputWriter (today: JsonlOutputWriter) for non-JSONL targets.

Troubleshooting

message cause / fix
unknown source alias 'x' An output/relationship references a sources key that doesn't exist.
join 'as': parent column 'c' not found in source 'a' on.parent isn't a column in the parent source. Check the header/spelling.
join 'as': child column 'c' not found in source 'b' on.child isn't a column in the child source.
keyedMap mode requires 'groupBy' / 'keyExpr' A keyedMap output is missing those fields.
unknown transform op 'x' Misspelled op, or a custom op not registered. See the catalog.
externalMerge requires all direct children … to join on the same parent column Switch that output to hashInMemory, or restructure so direct children share a parent key.
values land as strings when you expected numbers Declare the column's input type under the source's fields, or add a to* step.
a field is missing from the output Its value was null/empty (omitted by design), or its column name/from is wrong.
lookup column 'c' not found in source 's' The lookup's column or on.child isn't in that source; on.parent must be a column on the current row.
two relationships didn't merge into one array They must share the exact as name (and the resulting field renders after the node's scalar fields).
output property order looks wrong Order follows the fields array; reorder the entries (relationships always render after a node's fields).

See ETL-CONFIG.md for a terse schema reference.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.2.0 102 11/6/2026
2.1.0 95 11/3/2026
2.0.0 96 11/3/2026
1.0.0 112 10/13/2026