kelora 0.9.1

A command-line log analysis tool with embedded Rhai scripting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
# Absorb Functions

Absorb functions provide a streamlined way to extract structured data from event fields, merge it into the event, and (optionally) clean up the source field - all in a single operation.

## Overview

A common pattern in log processing is having mixed-content messages that contain both human-readable text and structured key-value data:

```
"Payment timeout order=1234 gateway=stripe duration=5s"
```

Traditionally, extracting this structured data requires multiple steps:

```rhai
// Traditional approach (3 steps)
let kv = e.msg.parse_kv()  // 1. Parse
e.merge(kv)                 // 2. Merge
e.msg = e.msg.before("order=")  // 3. Manually strip (complex!)
```

Absorb functions combine all these steps into one:

```rhai
// Absorb approach (1 step)
e.absorb_kv("msg")
// Result: e.msg = "Payment timeout", e.order = "1234", e.gateway = "stripe", e.duration = "5s"
```

**Important:** Absorb functions don't guess or infer structure—they extract key-value pairs that are already present in the text using explicit separators you control.

## absorb_kv()

Parse key-value pairs from an event field, merge them into the event, and update the field with unparsed text. Returns a status record so scripts can react without guessing.

### Signatures

Kelora standardizes on a single, options-driven call:

```rhai
absorb_kv(field: string, options: map = #{}) -> AbsorbResult
```

All optional behavior is expressed through the `options` map—there is no positional `sep`/`kv_sep` overload.

**Parameters:**

| Parameter | Type | Description |
|-----------|------|-------------|
| `field` | string | Field name to parse (e.g., `"msg"`) |
| `options` | map | Optional behavior tweaks (see below) |

### Options

Absorb functions share a common options map so scripts can set behavior once and reuse it across formats. Unknown option keys are rejected up front; format-specific parsers silently ignore valid-but-irrelevant keys (e.g., `sep` for JSON).

| Option | Type | Default | Applies to | Effect |
|--------|------|---------|-----------|--------|
| `sep` | string or `()` | Whitespace | Tokenized formats (KV, logfmt) | Token separator; use `()` for whitespace |
| `kv_sep` | string | `"="` | Tokenized formats (KV, logfmt) | Key-value separator |
| `keep_source` | bool | `false` | All | Leave the source field untouched; use the return value's `remainder` when you need the cleaned text |
| `overwrite` | bool | `true` | All | When `true`, parsed values overwrite existing event fields. When `false`, existing fields are preserved and conflicting keys are skipped during merge |

**Validation rules**

- The options map is validated against the table above. Unknown keys set `status = "invalid_option"` and populate `error` with `unknown absorb option: <key>`.
- In resilient mode the function returns the `AbsorbResult` so scripts can handle or log the error.
- `--strict` mode escalates immediately; the pipeline aborts on the first invalid option to keep failures loud.

### Return Value

`AbsorbResult` is a record with the following fields:

| Field | Type | Description |
|-------|------|-------------|
| `status` | string | One of `"applied"`, `"missing_field"`, `"not_string"`, `"empty"`, `"parse_error"`, or `"invalid_option"` |
| `data` | map | All parsed key-value pairs (only populated when `status == "applied"`) |
| `written` | bool | `true` when at least one parsed key actually mutated the event (respects `overwrite`) |
| `remainder` | string or `()` | The leftover text that was not parsed; `()` when no remainder |
| `removed_source` | bool | `true` when the field was deleted after parsing every token |
| `error` | string or `()` | Human-readable parse failure when `status == "parse_error"` or `"invalid_option"`; `()` otherwise |

**Status guide:**
- `applied`: At least one key-value pair was parsed. Check `written` to see if anything actually changed.
- `missing_field`: The target field is absent.
- `not_string`: The field exists but is not a string.
- `empty`: The field is a string but produced no pairs after trimming (covers whitespace-only and “no pairs” scenarios).
- `parse_error`: Parser rejected the payload (all-or-nothing formats) and the field was left untouched; `error` contains the message.
- `invalid_option`: The options map contained an unsupported key. Resilient mode returns the error; `--strict` aborts immediately.

**Note:** `AbsorbResult` is shared across all `absorb_*()` functions (JSON, logfmt, URL params, etc.). For all-or-nothing formats like JSON or URL parameters, `remainder` is always `()`, and `parse_error` includes a descriptive `error` string.

Method-style calls are still supported:

**Method-style calls supported:**
```rhai
e.absorb_kv("msg")           // As method on event map
absorb_kv(e, "msg")          // As function
```

### Behavior

The function performs these steps:

#### 1. Extract and Validate Field

- Get value of the specified field
- If field doesn't exist → return result with `status = "missing_field"`
- If field is not a string → return result with `status = "not_string"`

#### 2. Parse with Remainder Tracking

- Split text by separator (whitespace by default, or custom separator)
- For each token:
  - **Contains KV separator** (`=` by default): Parse as `key=value` pair
  - **Doesn't contain KV separator**: Keep as unparsed text

```rhai
"Payment timeout order=1234 gateway=stripe duration=5s"
// Tokens: ["Payment", "timeout", "order=1234", "gateway=stripe", "duration=5s"]
// Parsed data: {order: "1234", gateway: "stripe", duration: "5s"}
// Unparsed: ["Payment", "timeout"]
```

#### 3. Merge Parsed Pairs into Event

- Each parsed key-value pair is inserted into the event
- **Overwrites existing fields** with same key (like `merge()`) by default
- Set `overwrite: false` to preserve existing fields when conflicts occur

#### 4. Update Source Field

Unless `keep_source` is enabled, the source field is updated according to:

**Unparsed tokens remain:**
- Join unparsed tokens using the same separator that was used for splitting (`sep: ()` still normalizes whitespace to a single space)
- Update field with this remainder
```rhai
e.msg = "Payment timeout order=1234"
e.absorb_kv("msg")
// → e.msg = "Payment timeout"
```

**All tokens were pairs:**
- Delete field entirely
```rhai
e.data = "user=alice status=active"
e.absorb_kv("data")
// → e.data deleted (field removed from event)
```

When `keep_source` is `true`, the source field is never modified; use `res.remainder` if you need the cleaned text.

#### 5. Return Result

- Returns `AbsorbResult` so scripts can inspect `status`, `data`, `written`, and `remainder`
- `status == "applied"` when at least one pair was parsed
- `written == true` when at least one parsed key was written (helpful when `overwrite: false`)
- Non-`"applied"` statuses indicate why nothing changed

### Examples

#### Basic Usage

```rhai
e.msg = "Payment timeout order=1234 gateway=stripe duration=5s"
let res = e.absorb_kv("msg")

// After:
// e.msg = "Payment timeout"
// e.order = "1234"
// e.gateway = "stripe"
// e.duration = "5s"
// res.status == "applied"
// res.data == #{ order: "1234", gateway: "stripe", duration: "5s" }
// res.remainder == "Payment timeout"
// res.written == true
```

#### All Tokens Are Pairs

When every token is a key-value pair, the field is deleted:

```rhai
e.data = "user=alice status=active count=42"
let res = e.absorb_kv("data")

// After:
// e.data deleted (no longer exists)
// e.user = "alice"
// e.status = "active"
// e.count = "42"
// res.removed_source == true
// res.remainder == ()
```

#### No Pairs Found

If no key-value pairs are found, the field remains unchanged:

```rhai
e.msg = "This is just plain text without any pairs"
let res = e.absorb_kv("msg")

// After:
// e.msg = "This is just plain text without any pairs" (unchanged)
// res.status == "empty"
// res.data == #{}
// res.written == false
```

#### Custom Separators

Parse with custom token and KV separators:

```rhai
e.tags = "env:prod,region:us-west,tier:web"
let res = e.absorb_kv("tags", #{ sep: ",", kv_sep: ":" })

// After:
// e.tags deleted (all tokens were KV pairs)
// e.env = "prod"
// e.region = "us-west"
// e.tier = "web"
// res.status == "applied"
```

#### Custom Separator with Mixed Content

When mixing plain tokens and KV pairs, format is preserved:

```rhai
e.categories = "news,sports,user:alice,region:us-west"
let res = e.absorb_kv("categories", #{ sep: ",", kv_sep: ":" })

// After:
// e.categories = "news,sports" (comma-separated, format preserved!)
// e.user = "alice"
// e.region = "us-west"
// res.remainder == "news,sports"
```

#### Whitespace Separator with Custom KV Separator

Use `sep: ()` in the options map to specify whitespace separator with custom KV separator:

```rhai
e.labels = "env:prod region:us tier:web"
let res = e.absorb_kv("labels", #{ sep: (), kv_sep: ":" })

// After:
// e.labels deleted
// e.env = "prod"
// e.region = "us"
// e.tier = "web"
```

#### Keeping the Source Field

Prevent destructive updates by enabling `keep_source`:

```rhai
e.msg = "Payment timeout order=1234"
let res = e.absorb_kv("msg", #{ keep_source: true })

// After:
// e.msg stays "Payment timeout order=1234"
// e.order == "1234"
// res.remainder == "Payment timeout"
```

#### Avoiding Overwrites

Preserve existing fields by disabling overwrite:

```rhai
e.order = "legacy"
e.msg = "order=1234 duration=5s"
let res = e.absorb_kv("msg", #{ overwrite: false })

// After:
// e.order is still "legacy" (not overwritten)
// e.duration == "5s" (new field added)
// res.data == #{ order: "1234", duration: "5s" } (shows all parsed data)

assert(res.written)  // true because at least one new field landed

// All conflicts, nothing written:
e.msg = "order=999"
let res2 = e.absorb_kv("msg", #{ overwrite: false })
assert(res2.status == "applied")
assert(res2.written == false)
```

`res.data` always reports what was parsed, even if `overwrite: false` prevents conflicting keys from being written. Use `res.written` to quickly detect whether any mutation happened and only inspect the event map when you need per-field detail.

#### Conditional Logic

Use the return value for conditional processing:

```rhai
// Try KV first, fall back to JSON if no pairs
let res = e.absorb_kv("payload")
if res.status != "applied" {
    e.merge(e.payload.parse_json())
}
```

```rhai
// Only process events with KV data
let res = e.absorb_kv("msg")
if res.status == "applied" {
    print("Found structured data")
}
```

### Edge Cases

#### Field Doesn't Exist

No error; result reports `status = "missing_field"`:

```rhai
let res = e.absorb_kv("missing_field")
assert(res.status == "missing_field")
```

#### Field Is Not a String

No error; result reports `status = "not_string"`:

```rhai
e.count = 42
let res = e.absorb_kv("count")
assert(res.status == "not_string")
```

#### Empty or Whitespace-Only String

`status = "empty"` and the field is deleted (unless `keep_source` is set):

```rhai
e.msg = ""
let res = e.absorb_kv("msg")
assert(res.status == "empty")

e.msg = "   "
let res2 = e.absorb_kv("msg")
assert(res2.status == "empty")
```

#### Unknown Option

Typos are caught immediately:

```rhai
let res = e.absorb_kv("msg", #{ keep_sorce: true })
assert(res.status == "invalid_option")
assert(res.error == "unknown absorb option: keep_sorce")
```

In resilient mode you can branch on `res.status`; in `--strict` Kelora stops the pipeline on the same error.

#### Key with Empty Value

Empty values are preserved:

```rhai
e.msg = "error= code=500"
let res = e.absorb_kv("msg")

// After:
// e.msg deleted
// e.error = ""  (empty string)
// e.code = "500"
// res.data.error == ""
```

#### Key with No Value Separator

Tokens without the KV separator are kept as unparsed text:

```rhai
e.msg = "prefix key=value suffix"
let res = e.absorb_kv("msg")

// After:
// e.msg = "prefix suffix"
// e.key = "value"
// res.remainder == "prefix suffix"
```

#### Conflicting Keys (Overwrites)

By default absorb **overwrites existing fields** (same behavior as `merge()`), but `overwrite: false` preserves existing values:

```rhai
e.status = "pending"
e.msg = "Processing status=active"

// Default: overwrites existing
e.absorb_kv("msg")
assert(e.status == "active")        // overwritten

// Reset for second example
e.status = "pending"
e.msg = "Processing status=active"

// With overwrite: false, keeps existing
let res = e.absorb_kv("msg", #{ overwrite: false })
assert(res.data.status == "active") // parsed data available
assert(e.status == "pending")       // unchanged - existing preserved
```

#### Special Characters and Unicode

Handles Unicode and special characters in both keys and values:

```rhai
e.msg = "user=alice™ emoji=🎉 price=$99.99"
let res = e.absorb_kv("msg")

// After:
// e.msg deleted
// e.user = "alice™"
// e.emoji = "🎉"
// e.price = "$99.99"
// res.data.price == "$99.99"
```

### Comparison with Manual Approach

#### Before: Manual Parse + Merge

```rhai
e.msg = "Payment timeout order=1234 gateway=stripe"

// Step 1: Parse
let kv = e.msg.parse_kv()  // {order: "1234", gateway: "stripe"}

// Step 2: Merge
e.merge(kv)

// Step 3: Clean up (complex!)
// Problem: e.msg still = "Payment timeout order=1234 gateway=stripe"
// Need manual string manipulation:
e.msg = e.msg.before("order=").strip()  // Fragile! What if order appears in text?
// Or complex regex replacement...
```

#### After: Single Absorb Call

```rhai
e.msg = "Payment timeout order=1234 gateway=stripe"
e.absorb_kv("msg")

// Done!
// e.msg = "Payment timeout"
// e.order = "1234", e.gateway = "stripe"
```

### Implementation Notes

#### Join Separator for Unparsed Tokens

Unparsed tokens are **joined using the same separator that was used for splitting**.

**Rationale:**
- Preserves format fidelity (comma-separated stays comma-separated)
- Enables round-tripping and further processing
- Whitespace mode still normalizes to single space (expected behavior)

**Rules:**
- **Whitespace mode** (`sep = ()`): Join with single space
- **Custom separator** (`sep = ","`, `":"`, etc.): Join with same separator
- **Token processing**: Tokens are trimmed before classification; empty tokens are filtered out

**Example with custom separator:**
```rhai
e.tags = "important,urgent,user=alice,priority=high"
e.absorb_kv("tags", #{ sep: ",", kv_sep: "=" })

// Unparsed: ["important", "urgent"]
// Joined with comma (same as split separator):
// e.tags = "important,urgent"
```

**Example with whitespace:**
```rhai
e.msg = "Error   occurred    code=500"
e.absorb_kv("msg")

// Unparsed: ["Error", "occurred"]
// Joined with single space (normalized):
// e.msg = "Error occurred"
```

#### Token Processing and Normalization

Before classifying tokens as KV pairs or remainder, each token undergoes processing:

**Steps:**
1. **Split** by separator (whitespace or custom string)
2. **Trim** each token (remove leading/trailing whitespace)
3. **Filter** empty tokens (from consecutive separators like `"tag1,,tag3"`)
4. **Classify** as KV pair (contains `kv_sep`) or remainder
5. **Join** remainder using same separator

**Edge cases handled:**

```rhai
// Leading/trailing separators
e.data = ",tag1,tag2,owner=alice,"
e.absorb_kv("data", #{ sep: ",", kv_sep: "=" })
// Split: ["", "tag1", "tag2", "owner=alice", ""]
// After trim+filter: ["tag1", "tag2", "owner=alice"]
// Result: e.data = "tag1,tag2"

// Inconsistent spacing with custom separator
e.tags = "error, warning, code=500"
e.absorb_kv("tags", #{ sep: ",", kv_sep: "=" })
// Split: ["error", " warning", " code=500"]
// After trim: ["error", "warning", "code=500"]
// Classified: KV={code:"500"}, remainder=["error","warning"]
// Result: e.tags = "error,warning"

// Whitespace mode normalizes all whitespace
e.msg = "Error\n\toccurred\t\tuser=alice"
e.absorb_kv("msg")
// Split by any whitespace: ["Error", "occurred", "user=alice"]
// Remainder joined with single space: "Error occurred"
```

#### Error Handling

Follows Kelora's resilient error handling philosophy:

- **Never throws exceptions** in resilient mode
- Invalid field types → `status = "not_string"`, no error
- Missing fields → `status = "missing_field"`, no error
- Empty results → `status = "empty"`, not an error
- Parsers that fail (e.g., logfmt quotes, JSON syntax) return `status = "parse_error"` and populate `error` with the failure message

This ensures `absorb_kv()` can be used safely in pipelines without breaking on unexpected data.

#### Performance

The function performs a single pass through the text:
1. One split operation
2. One pass to classify tokens (pair vs. unparsed)
3. Insertion into event map (O(1) per key)
4. One join for unparsed tokens

Overall: O(n) where n is the number of tokens. `written` is tracked inside the merge loop, so there is no extra pass or allocation.

## Future Extensions

The absorb pattern can be extended to other formats:

### absorb_json()

Parse JSON from field, merge into event, delete field:

```rhai
e.payload = '{"user":"alice","action":"login","timestamp":1234567890}'
let res = e.absorb_json("payload")

// After:
// e.payload deleted
// e.user = "alice"
// e.action = "login"
// e.timestamp = 1234567890
// res.status == "applied"
// res.data == #{ user: "alice", action: "login", timestamp: 1234567890 }
// res.remainder == ()  (always () for JSON)
```

**Options:** Supports the shared options map. `keep_source` lets you retain the original JSON string, and `overwrite` controls merge conflicts. `sep` / `kv_sep` are ignored.

**Behavior differences from absorb_kv():**
- JSON parsing is all-or-nothing (no "unparsed text")
- Field always deleted on successful parse
- Parse failure → `status = "parse_error"`, field unchanged, and `res.error` carries the parser message

### absorb_logfmt()

Parse logfmt from field, merge into event, clean field:

```rhai
e.msg = 'prefix user="alice" status=active suffix'
let res = e.absorb_logfmt("msg")

// After:
// e.msg = "prefix suffix"
// e.user = "alice"
// e.status = "active"
// res.status == "applied"
// res.data == #{ user: "alice", status: "active" }
// res.remainder == "prefix suffix"
```

**Options:** Honors the same options map. `sep`/`kv_sep` customize token parsing, while `keep_source` and `overwrite` behave identically to `absorb_kv()`.

**Similar to absorb_kv()** but uses logfmt parser which handles quoted values.

### absorb_url_params()

Parse URL query parameters from field, merge into event, delete field:

```rhai
e.query = "foo=bar&baz=qux&limit=10"
let res = e.absorb_url_params("query")

// After:
// e.query deleted
// e.foo = "bar"
// e.baz = "qux"
// e.limit = "10"
// res.status == "applied"
// res.data == #{ foo: "bar", baz: "qux", limit: "10" }
// res.remainder == ()  (always () for URL params)
```

**Options:** Shares the same options map. `keep_source` preserves the original query string, `overwrite` guards existing fields, and tokenization options are ignored.

**All-or-nothing parsing** like JSON - entire string is the query string.
- Parse failure → `status = "parse_error"`, field unchanged, and `res.error` carries the parser message.

### Format-Specific Behavior Summary

| Format | Unparsed Text Behavior | Field Deletion |
|--------|------------------------|----------------|
| **KV** | Kept in field | Only if all tokens are pairs |
| **Logfmt** | Kept in field | Only if entire string is logfmt |
| **JSON** | N/A (all-or-nothing) | Always on success |
| **URL params** | N/A (all-or-nothing) | Always on success |

## See Also

- [parse_kv()]../reference/cli-reference.md#parse_kv - Parse KV pairs without modifying source
- [merge()]../reference/cli-reference.md#merge - Merge maps into events
- [Error Handling]../concepts/error-handling.md - Kelora's error handling philosophy
- [Rhai Functions]../reference/rhai-functions.md - Complete function reference