Skip to content

Examples and workflows

Five practical acdat recipes: resolving overlapping phrases, extracting log IOCs with a reverse-lookup index, rolling out versioned dictionaries atomically, scanning binary payloads, and shipping compiled artifacts across databases.

Every example below is self-contained and runs inside PostgreSQL using acdat v0.1.1.

1. Overlapping rules and redaction policies

Real dictionaries almost always contain overlapping phrases—for instance, "credit card", "credit card fraud", and "fraud". acdat resolves overlaps deterministically using three policies:

  • all_overlapping (default for matches): reports every candidate hit, including prefixes, suffixes, and duplicate text with distinct IDs.
  • leftmost_longest (default for replace): consumes the leftmost match; at the same start offset, prefers the longer pattern, then lower priority number, then lower ID.
  • leftmost_priority: consumes the leftmost match; at the same start offset, prefers the lower priority number first (e.g., priority 10 beats priority 20), then longer pattern, then lower ID.
WITH dict AS (
    SELECT acdat.compile(
        ARRAY['credit card', 'credit card fraud', 'fraud'],
        ARRAY[1, 2, 3]::bigint[],
        ARRAY['[PAYMENT]', '[HIGH-RISK]', '[RISK]'],
        ARRAY[10, 20, 5]::integer[]
    ) AS m
)
SELECT
    acdat.replace('report credit card fraud now', m, 'leftmost_longest')  AS longest,
    acdat.replace('report credit card fraud now', m, 'leftmost_priority') AS by_priority,
    (SELECT count(*) FROM acdat.matches('report credit card fraud now', m, 'all_overlapping')) AS total_hits
FROM dict;
         longest         |         by_priority         | total_hits
-------------------------+-----------------------------+------------
 report [HIGH-RISK] now  | report [PAYMENT] [RISK] now |          3

Why the two results differ:

  • Under leftmost_longest, "credit card fraud" (17 bytes) beats "credit card" (11 bytes) at byte 8 and consumes the entire span.
  • Under leftmost_priority, "credit card" (priority 10) beats "credit card fraud" (priority 20) at byte 8; scanning then resumes after byte 18 and also matches "fraud".

Practical rules for acdat.replace():

  • Delete spans with '': An empty replacement string deletes the matched span; selecting a rule whose replacement is NULL raises an error (acdat pattern ID <n> has no replacement).
  • Single non-recursive pass: Replacement output is never rescanned, so replacing "foo" with "foobar" cannot loop.
  • Guard against expansion: Pass explicit max_replacements (default 10000) and max_output_bytes (default 256 MiB) when short inputs could expand into large outputs. The candidate limit counts raw overlaps before policy resolution, and an outer SQL LIMIT does not cap it.

2. Extract log IOCs and build a reverse-lookup table

When auditing security logs or tagging documents against a large IOC (Indicator of Compromise) list, you often need two answers: “which indicators hit this log?” and later “which logs matched indicator #402?”

CREATE TEMP TABLE ioc_rules (
    pattern_id bigint PRIMARY KEY,
    pattern    text NOT NULL,
    severity   text NOT NULL
);

INSERT INTO ioc_rules VALUES
    (401, 'malicious.example', 'critical'),
    (402, '198.51.100.77',     'high'),
    (403, 'powershell -enc',   'critical');

CREATE TEMP TABLE ioc_machine AS
SELECT acdat.compile(pattern, pattern_id) AS machine
FROM ioc_rules;

CREATE TEMP TABLE access_logs (
    log_id bigint PRIMARY KEY,
    line   text NOT NULL
);

INSERT INTO access_logs VALUES
    (1, 'GET https://malicious.example/payload from 198.51.100.77'),
    (2, 'GET https://docs.example.org/index.html from 203.0.113.5'),
    (3, 'exec: PowerShell -Enc SQBFAFgA');

Notice log #3 has mixed casing (PowerShell -Enc). Because acdat compares exact UTF-8 bytes without case folding or Unicode normalization, normalize both rules and input identically (for example with lower()) when case-insensitive matching is required:

-- Materialize every hit along with position offsets for auditing and reverse lookup
CREATE TEMP TABLE log_ioc_hits AS
SELECT l.log_id,
       h.pattern_id,
       r.severity,
       h.start_byte,
       h.byte_length,
       h.start_char,
       h.char_length,
       substring(lower(l.line) FROM h.start_char FOR h.char_length) AS matched_token
FROM access_logs AS l
CROSS JOIN LATERAL acdat.matches(
    lower(l.line),
    (SELECT machine FROM ioc_machine),
    'all_overlapping',
    1000
) AS h
JOIN ioc_rules AS r USING (pattern_id);

CREATE INDEX ON log_ioc_hits (pattern_id, log_id);

SELECT log_id, pattern_id, severity, start_char, char_length, matched_token
FROM log_ioc_hits
ORDER BY log_id, start_byte;
 log_id | pattern_id | severity | start_char | char_length |   matched_token
--------+------------+----------+------------+-------------+-------------------
      1 |        401 | critical |         13 |          17 | malicious.example
      1 |        402 | high     |         44 |          13 | 198.51.100.77
      3 |        403 | critical |          7 |          15 | powershell -enc

With the index on (pattern_id, log_id), reverse lookups (WHERE pattern_id = 402) are instant. In production, store dictionary_version and build_id alongside each materialized hit so you know which rule build produced it and can rebuild cleanly when rules change.

Note

Offsets are 1-based. For UTF-8 text, start_byte/byte_length measure UTF-8 bytes while start_char/char_length measure Unicode code points (which plug directly into PostgreSQL substring(... FROM start_char FOR char_length)). Always add ORDER BY if you need stable output order.

3. Publish, atomically switch, and roll back dictionaries

For production dictionaries that change over time, use acdat’s built-in catalog instead of overwriting a single row. Publishing stores an immutable semantic version and returns a 32-byte build_id; activating flips a pointer in acdat.active_dictionary atomically under MVCC so concurrent readers switch cleanly without locks.

-- 1. Compile and publish version 1 from your rule table
CREATE TEMP TABLE dict_releases (version bigint PRIMARY KEY, build_id bytea NOT NULL);

INSERT INTO dict_releases (version, build_id)
SELECT 1,
       acdat.publish(
           'security_ioc',
           1,
           acdat.compile(pattern, pattern_id),
           '{"ticket":"SEC-101"}'::jsonb
       )
FROM ioc_rules;

-- 2. Activate version 1
SELECT acdat.activate('security_ioc', build_id)
FROM dict_releases WHERE version = 1;

-- 3. Add a new rule, publish version 2, and switch traffic atomically
INSERT INTO ioc_rules VALUES (404, 'credential-dump', 'critical');

INSERT INTO dict_releases (version, build_id)
SELECT 2,
       acdat.publish(
           'security_ioc',
           2,
           acdat.compile(pattern, pattern_id),
           '{"ticket":"SEC-102"}'::jsonb
       )
FROM ioc_rules;

SELECT acdat.activate('security_ioc', build_id)
FROM dict_releases WHERE version = 2;

-- Readers always query acdat.active_machine
SELECT name, version, acdat.contains('detected credential-dump', machine) AS hit
FROM acdat.active_machine
WHERE name = 'security_ioc';
     name     | version | hit
--------------+---------+-----
 security_ioc |       2 | t

If version 2 triggers false positives, roll back immediately by reactivating version 1, then retire version 2:

SELECT acdat.activate('security_ioc', build_id)     FROM dict_releases WHERE version = 1;
SELECT acdat.retire_build('security_ioc', build_id) FROM dict_releases WHERE version = 2;

Keep these compilation rules in mind:

  • Parallel arrays passed to acdat.compile() must be 1D and equal in length; patterns must be non-empty; explicit IDs must be non-NULL and unique (duplicate literal strings with distinct IDs are allowed); NULL priorities default to 0.
  • An aggregate over zero rows returns NULL; an explicitly typed empty array (ARRAY[]::text[]) builds an empty machine.
  • Canonical sorting makes source_fingerprint() independent of input row order when rule IDs are stable.

4. Scan and patch binary payloads (bytea)

Use the bytea overloads to match protocol headers, file magic bytes, or raw signatures containing \x00 or non-UTF-8 octets. Binary hits always return NULL for start_char and char_length.

WITH sigs AS (
    SELECT acdat.compile(
        ARRAY[decode('00ff', 'hex'), decode('beef', 'hex')],
        ARRAY[20, 21]::bigint[],
        ARRAY[decode('1122', 'hex'), decode('dead', 'hex')]
    ) AS m
)
SELECT
    (SELECT array_agg(pattern_id ORDER BY start_byte)
     FROM acdat.matches(decode('aa00ffbeef', 'hex'), m)) AS hit_ids,
    encode(acdat.replace(decode('aa00ffbeef', 'hex'), m), 'hex') AS patched
FROM sigs;
 hit_ids |  patched
---------+------------
 {20,21} | aa1122dead

Text machines reject bytea inputs and vice versa (acdat machine input kind does not match function input). On databases using encodings other than UTF8 or single-byte encodings, use bytea.

5. Inspect and ship compiled machines across databases

If you compile a 100,000-pattern dictionary in CI or on a build server, you can inspect its metadata and ship the compiled bytea artifact to production databases without recompiling there.

WITH d AS (
    SELECT acdat.compile(ARRAY['virus', 'signature'], ARRAY[1, 2]::bigint[]) AS m
)
SELECT acdat.info(m)->>'engine'                         AS engine,
       acdat.info(m)->>'pattern_count'                  AS patterns,
       encode(acdat.source_fingerprint(m), 'hex')       AS source_sha256,
       encode(acdat.artifact_checksum(m),  'hex')       AS artifact_sha256
FROM d;

Export on the build database, validate and import on the target database:

WITH exported AS (
    SELECT acdat.export(acdat.compile(ARRAY['virus', 'signature'])) AS blob
)
SELECT acdat.validate(blob) AS valid,
       acdat.contains('virus detected', acdat.import(blob)) AS works
FROM exported;
 valid | works
-------+-------
 t     | t
  • source_fingerprint() hashes the canonical rule set; build_fingerprint() also includes engine, compiler, and format version; artifact_checksum() hashes the serialized payload.
  • validate() returns false on corrupted bytes while import() raises an error.
  • Transfer text machines only between databases with compatible server encodings; bytea machines are encoding-independent.