DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • First Native LLM Fine-Tuned for the Telecom Industry
  • Idempotent Consumers: Preventing Stale Retries With Version-Fenced Writes
  • MySQL Instant DDL: Metadata Locks, Waiting Writers, and Query Pileups
  • Taming Parameter Sniffing in SQL Server 2022 With PSP Optimization

Trending

  • Why Successful LLM Demos Fail in Production
  • How Has AI Impacted Code Obfuscation?
  • Seven AI Adoption Failures and How to Overcome Them
  • An Introduction to OpenID AuthZEN and authzen-enforcer, a Java SDK

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Databases
  4. Telling a Language Model What a Fraud Ring Looks Like: A Snowflake Experiment

Telling a Language Model What a Fraud Ring Looks Like: A Snowflake Experiment

A model that is told what separates a ring from a decoy catches almost every real ring with few false alarms. A model that is not informed floods reviewers.

By 
Akmal Chaudhri
DZone Core CORE ·
Dec. 02, 26 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
95 Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Fraud rings are closed loops of payments: account A pays B, B pays C, and C pays A, usually for almost the same amount, and often within hours. Ordinary traffic produces loops by chance, so finding a loop is easy, and deciding whether it is a ring is the hard part.

This article builds a small experiment around that question. We generate a synthetic payments dataset in Snowflake with a known set of rings and a deliberate set of decoys. We find every candidate loop with a SQL query that runs in the database. We then ask a hosted model (Jev from TypeSafe AI) to judge each loop twice: once with a bare question, and once with a guided question that explains what to look for. Finally, we score both answers against the hidden ground truth and compare them with two plain rules that use no model at all.

The short answer: guidance matters a great deal, and a well-crafted rule is a strong contender. Read on for more details, including a few things that went wrong on the way.

What We Are Building

The project is two Jupyter notebooks that run on your own machine and connect to Snowflake remotely:

  • The first notebook creates the ACCOUNTS and TRANSACTIONS tables, with planted rings and decoys.
  • The second notebook finds candidate loops in SQL, asks the model to judge a sample of them and scores the answers.

The flow for each run looks like this:

  1. The generator writes the data to Snowflake and reads it back to check it.
  2. The triage notebook runs a self-join query in Snowflake that returns every closed loop of three or four accounts, with its timing and amount ratio computed in the database.
  3. Each loop becomes a small record: the amounts, the minutes between transfers, the account risk scores and a few summary numbers. The record holds no account ids, customer names, transaction ids or fraud label.
  4. The model answers a bare question and a guided question for each loop in a sample.
  5. We score the answers against the IS_FRAUD_RING label, which the model never sees.

The notebooks support three model modes: hosted (Jev over the internet), local (a model served by Ollama on your machine), and replay (answers saved from an earlier hosted run, so the notebook runs with no model access). All results in this article come from the hosted model.

Prerequisites

You'll need:

  • Python and Jupyter on your machine, running in a virtual environment (venv).
  • A Snowflake account and a role that can create a database and a warehouse. SYSADMIN works.
  • Key-pair login set up for your Snowflake user (refer to the Gotchas section).
  • A TypeSafe API key for hosted mode. Replay mode needs no key.

Set the following environment variables before launching Jupyter:

Shell
 
export SNOWFLAKE_ACCOUNT="<your-account-identifier>"
export SNOWFLAKE_USER="<your-user>"
export SNOWFLAKE_PRIVATE_KEY_PATH="rsa_key.p8"
export SNOWFLAKE_ROLE="SYSADMIN"
export SNOWFLAKE_WAREHOUSE="FRAUD_RING_WH"
export TYPESAFE_API_KEY="<your-api-key>"


The database defaults to FRAUD_RING_DEMO and the schema to PUBLIC. Set SNOWFLAKE_DATABASE or SNOWFLAKE_SCHEMA to change them. If your key has a passphrase, set the SNOWFLAKE_PRIVATE_KEY_PASSPHRASE as well. Newer Snowflake accounts may block single-factor password login, so key-pair login is the safer choice.

Creating the Key-Pair

Generate a private key in PKCS8 format and derive the public key from it using OpenSSL:

Shell
 
openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out rsa_key.p8 -nocrypt
openssl rsa -in rsa_key.p8 -pubout -out rsa_key.pub


The first command writes the private key to rsa_key.p8, which is the file SNOWFLAKE_PRIVATE_KEY_PATH points to. Keep it secret and never commit it to the repository. If you would rather protect it with a passphrase, remove -nocrypt from the first command. OpenSSL will then prompt for a passphrase, and you must also set SNOWFLAKE_PRIVATE_KEY_PASSPHRASE.

Registering the Public Key

Print the public key body on one line, without the header and footer lines:

Shell
 
grep -v "PUBLIC KEY" rsa_key.pub | tr -d '\n'


Copy that output. Paste only this key body into Snowflake, leaving out the -----BEGIN PUBLIC KEY----- and -----END PUBLIC KEY----- lines. Then set it on your user:

SQL
 
SET my_username = CURRENT_USER();
ALTER USER IDENTIFIER($my_username) SET RSA_PUBLIC_KEY='<your-public-key>';


To confirm the registration, check that the user now has a key fingerprint:

SQL
 
DESC USER IDENTIFIER($my_username);


Look for a value in the RSA_PUBLIC_KEY_FP row. You may need to run ALTER USER as a role that can modify your user, such as SECURITYADMIN or ACCOUNTADMIN.

The Two Snowflake Tables

The generator creates two tables. Both are fully synthetic and the same seed always produces the same data:

Table Columns
ACCOUNTS ACCOUNT_ID, CUSTOMER_NAME, RISK_SCORE
TRANSACTIONS TX_ID, SOURCE_ACCOUNT_ID, TARGET_ACCOUNT_ID, AMOUNT, TIMESTAMP, DESCRIPTION, IS_FRAUD_RING


TIMESTAMP is a real TIMESTAMP_NTZ, and IS_FRAUD_RING is the text 'True' or 'False'. Every transfer that belongs to a real ring is flagged there, which gives us the ground truth.

The default dataset has 1,000 accounts and 50,000 background transactions, which are random transfers between random accounts. The loops are added on top. The first dataset ends up with 50,271 transactions, 191 of them real-ring transfers in 45 real rings. Transaction IDs are assigned after everything is shuffled together, so an ID says nothing about whether a transfer belongs to a ring. Each loop uses its own accounts, and no account appears in two loops.

The Rings and the Decoys

An easy dataset would not teach us much. In our first version, the guided question and a simple timing rule both scored 100 percent, which told us the data was too easy. So the generator plants five kinds of loops:

Kind Count Timing Amounts Account Risk Real Ring?
ring 33 Minutes apart Within about 3% 0.35 to 0.95 Yes
lookalike 10 Minutes apart Within about 3% 0.05 to 0.55 No
uneven_fast 10 Minutes apart At least 10% apart 0.01 to 0.99 No
slow_ring 6 One to three days apart Within about 3% 0.35 to 0.95 Yes
uneven_ring 6 Minutes apart About 4% to 14% apart 0.60 to 0.95 Yes


The kinds are chosen so that no single signal separates rings from decoys:

  • A timing rule finds the fast, near-equal rings but also the look-alikes, and it misses the slow rings.
  • Equal amounts alone catch the look-alikes too.
  • Risk scores overlap between real rings and look-alikes in the 0.35 to 0.55 band.
  • A tight amount cut-off misses the moderately uneven real rings.

The hard cases are on by default. In the data generator notebook, set INCLUDE_HARD_CASES = False to get only the real rings.

Finding Candidate Loops in SQL

The triage notebook does not ask the model to find loops. Snowflake does that with a self-join on the transactions table. For three-account loops, the query looks like the following, trimmed for space:

SQL
 
WITH in_window AS (
    SELECT tx_id, source_account_id, target_account_id, amount, timestamp, is_fraud_ring
    FROM FRAUD_RING_DEMO.PUBLIC.TRANSACTIONS
    WHERE amount > 3000.0 AND amount < 10000.0
)
SELECT t1.tx_id, t2.tx_id, t3.tx_id, ...
FROM in_window t1
JOIN in_window t2 ON t1.target_account_id = t2.source_account_id
JOIN in_window t3 ON t2.target_account_id = t3.source_account_id
WHERE t3.target_account_id = t1.source_account_id
  AND t1.source_account_id < t2.source_account_id
  AND t1.source_account_id < t3.source_account_id
  AND t2.source_account_id <> t3.source_account_id


The query starts each loop at its lowest account ID, so it finds every loop once. The outer query adds the span in hours, the ratio of the largest to the smallest amount, and a flag for whether every leg is labeled as fraud. That flag is the ground truth, and it is never sent to the model.

By default, the notebook searches for rings of three and four accounts. The search takes under a second on an X-Small warehouse. Larger rings can produce tens of thousands of candidates, so the MAX_AMOUNT_RATIO keeps the search small if you raise HOPS_MAX.

On the first dataset, the search returns 861 candidates: 165 three-account loops and 696 four-account loops. Only 24 of them (2.8 percent) are real rings. The rest are chance loops and decoys.

What the Model Sees

Each loop becomes a small record. The following shows one of the sampled loops:

JSON
 
{
  "context": "A closed cycle of money transfers between bank accounts: each account pays the next one, and the last pays the first.",
  "accounts_in_cycle": 4,
  "transfers": [
    {"hop": 1, "amount": 9627.21, "minutes_after_first_transfer": 89},
    {"hop": 2, "amount": 9681.66, "minutes_after_first_transfer": 155},
    {"hop": 3, "amount": 9733.96, "minutes_after_first_transfer": 244},
    {"hop": 4, "amount": 9724.9,  "minutes_after_first_transfer": 0}
  ],
  "account_risk_scores": [0.59, 0.62, 0.58, 0.68],
  "average_account_risk": 0.62,
  "total_span_hours": 4.07,
  "largest_to_smallest_amount_ratio": 1.011
}


In hosted mode, this record is what leaves your machine. It holds amounts, minutes between transfers, risk scores, and the account count. It does not hold account IDs, customer names, transaction IDs, or the fraud label.

The Questions

We ask three questions. The first two are choices, and the third is a score.

The bare question gives the model the record and asks whether it looks like a deliberate money-laundering ring or a coincidental cycle, with no hint about what separates them. The model can answer likely_ring, coincidental_cycle, or needs_review.

The guided question asks the same thing, but tells the model what to weigh. It gives rough bands for the amount ratio and the average risk and says that timing is only a hint:

Python
 
GUIDED_QUESTION = Choice(
    instructions=(
        "Does this cycle of transfers look like a deliberate money-laundering ring, or a coincidental cycle "
        "in ordinary traffic? Judge it on amounts and risk together.\n"
        "Amounts: largest_to_smallest_amount_ratio up to about 1.03 is near-equal. Up to about 1.15 is moderately "
        "uneven. Above about 1.15 is clearly uneven, and then it is not a ring whatever the risk says.\n"
        "Risk: average_account_risk above 0.45 is high, below 0.35 is low, and between 0.35 and 0.45 is middling.\n"
        "Decide like this. Amounts up to about 1.15 and high risk: a ring. Near-equal amounts and low risk: a "
        "legitimate cycle. Only a middling average risk: needs review.\n"
        "Timing is only a hint. Many rings finish within hours, but some take days between transfers, so a long "
        "span alone does not rule a ring out."
    ),
    criteria={ ... },
)


The urgency score asks how soon an investigator should look at a loop using the same bands. The notebook ranks loops by this, but this article does not evaluate that ranking.

The Baselines

A model call is only worth it if the call beats a rule, or does something a rule cannot. We compare against two rules that use no model:

  • The timing rule flags a loop when its span is within 24 hours, and its amount ratio is within 1.032.
  • The amounts and risk rule ignores timing, flags a loop when its amount ratio is within 1.032, and its average account risk is at least 0.5.

The second rule is deliberately strong. We added it after seeing that the data was separable on those two features. The model is compared against the best simple alternative, not against a weak one.

The Sample

We do not send all 861 candidates to the model. The notebook sends a sample of 100 loops, built in three steps:

  1. Send all the real rings, up to half the sample.
  2. Send the most tricky non-rings, which are loops that finish within the rule's time window without being real rings. These take up to 30 percent of the sample.
  3. Send a random draw from everything else.

The second step matters more than it looks. When we first sampled the non-rings at random, the timing rule scored a perfect 1.0 on the sample, and 0.68 on all candidates. The look-alike decoys seldom landed in the sample. Reserving part of the sample for fast non-rings fixed that. The rules now score the same on the sample as on the full population. So the sample represents the difficulty.

The sample for the first dataset held all of the 24 real rings and 12 fast non-rings.

Running the Notebooks

Run the generator first. It connects, creates the database and warehouse if they are missing, and then:

  1. Checks that the two tables do not already exist,
  2. Generates the data,
  3. Loads it with write_pandas, 
  4. Reads it back and compares row counts, the number of real-ring transfers, the sum of the amounts, and the earliest and latest timestamps.

You should see:

Plain Text
 
FRAUD_RING_DEMO.PUBLIC is ready: 50,271 transactions, 191 of them in 45 real rings.


Then run the triage notebook. Set MODE to hosted, local or replay in section 3. A 100-loop sample takes a few seconds per question with the hosted model. At the end of the run, the notebook can save the hosted answers to a replay file. You can rerun the whole comparison later with no model access.

To rerun a notebook against existing tables, note that the generator will stop with a plain message and change nothing. To replace them, set REPLACE_TABLES_IN to the exact target, for example "FRAUD_RING_DEMO.PUBLIC", and run again. The notebook lists the tables with their row counts and confirms the role can create tables before it replaces anything. Set the variable back to None afterwards.

The Held-Out Dataset

The guidance contains numbers, such as 1.15 and 0.45, which we chose after looking at the first dataset. That raises an obvious question: does the guidance work only because it was tailored to this data?

To test that, each notebook has a HELDOUT switch. In the generator, HELDOUT = True builds a second dataset with a different seed and shifted ranges. Real-ring risk drops to 0.30 to 0.90, look-alike risk rises to 0.10 to 0.60, and the moderately uneven rings are slightly more uneven. The data is written to its own schema (HELDOUT) so the first dataset stays in place. In the triage notebook, HELDOUT = True reads from that schema and keeps a separate replay file. The guidance is not retuned.

The second dataset has 50,267 transactions, 186 real-ring transfers and 854 candidate loops (of which 27 are real rings).

Results on the First Dataset

The following table displays the results on the 100-loop sample. A loop counts as flagged when the answer is likely_ring:

Method Flagged Real Rings Caught False Alarms Precision Recall
Bare question 37 23 of 24 14 0.622 0.958
Guided question 25 23 of 24 2 0.920 0.958
Timing rule 25 17 of 24 8 0.680 0.708
Amounts and risk rule 19 19 of 24 0 1.000 0.792


The bare question method finds 23 of the 24 real rings, but pay for it with 14 false alarms (compared to 2 for the guided question). The guided question catches four more real rings than the amounts and risk rule, at the cost of two false alarms. It also finds the slow rings and the moderately uneven rings that the other rules miss. This is because the guidance tells it that timing is only a hint, and that moderately uneven amounts can still be a ring.

The timing rule is the weakest. It misses seven real rings and raises eight false alarms.

There is one more comparison worth looking at. If every needs_review answer goes to a person:

Method Loops Sent to a Person Real Rings Reached False Alarms
Guided question, flagged or sent to review 29 24 of 24 5
Amounts and risk rule 19 19 of 24 0


The guided question reaches all 24 real rings, and a person opens 29 loops to do it. The amounts and risk rule reaches 19 of 24 from 19 loops. Whether the extra ten loops are worth the five extra rings depends on what a missed ring costs.

Results on the Held-Out Dataset

Here is the same notebook run against the held-out schema, with no change to the guidance:

Method Flagged Real Rings Caught False Alarms Precision Recall
Bare question 33 24 of 27 9 0.727 0.889
Guided question 28 26 of 27 2 0.929 0.963
Timing rule 25 19 of 27 6 0.760 0.704
Amounts and risk rule 23 22 of 27 1 0.957 0.815


The shape of the result is the same. The guided question lands at 0.929 precision and 0.963 recall, against 0.920 and 0.958 for the first dataset. It catches four more real rings than the amounts and risk rule, against one more false alarm. Sent for review, the guided question reaches all 27 real rings from 31 loops, while the amounts and risk rule catches 22 of 27 from 23 flagged.

What Went Wrong on the Way

The guidance went through several versions, and the numbers show why we did not stop at the first one. The samples differ between rows, so read the table as indicative:

Guidance Guided Precision Guided Recall What Happened
Timing-based: a span over a day is a coincidence 0.944 0.850 Missed every slow ring. Matched the timing rule.
Amounts and risk, in words 0.947 0.900 Better, but flagged a loop with a ratio of 1.20.
Bands, with "high risk" meaning scores mostly above 0.6 1.000 0.333 Over-cautious. Sent 16 of 24 real rings to review.
Bands on the average risk, with 0.45 as high 0.920 0.958 The final version.


The third row is the instructive one. The model followed our bands faithfully, and the bands were wrong. Our real rings start at a risk of 0.35, so a threshold of 0.6 put most of them in the middling band, and the model compliantly sent them to review. The fix was twofold. We added an average_account_risk field to each record (so the model does not have to do the arithmetic), and we put the high threshold at 0.45, where the data actually separate.

A language model applies the thresholds you give it literally. If they are wrong, the answers will be wrong consistently and decisively.

Conclusions

On two synthetic datasets, built with different seeds and different risk ranges, we found the following:

  • Guidance is worth more than the model alone. The same model, asked the same question with and without guidance, cuts false alarms from 14 to 2 on the first dataset and from 9 to 2 on the second, at equal or better recall.
  • The guided model beats the best simple rule on recall. It catches four more real rings than the amounts and risk rule on both datasets, including the slow and moderately uneven rings that a tight cut-off cannot find.
  • The rule keeps the edge on precision. With zero or one false alarm, the amounts and risk rule is the more precise method, and it needs no model.
  • A mixed answer is useful. Counting needs_review as an escalation, the guided question reaches every real ring on both datasets, which a rule with a cut-off cannot do.
  • The sample should reflect the difficulty. A random sample of non-rings hides the decoys and flatters the rules.

Caveats

  • Synthetic data. The data have the structure we gave them. These results show that guidance carries across draws of the same generator, not that it works on real transactions.
  • Small samples. Each run has 24 to 27 real rings, so a difference of a loop or two is noise. The model's answers can also shift a little between runs: the bare question gave 22, and then 23 real rings were caught on the same data.
  • The guidance is tuned to the data. The bands encode the generator's ranges. The held-out test shows they survive a shift, but it was modest, and we did not retune.
  • Only the hosted model was measured. The local mode (which uses a small Ollama model) exists in the notebook, but we did not run its results here.
  • The urgency score is unevaluated. The notebook ranks loops by it, but we did not assess the ranking.
  • A rule can be strict. Two features and two thresholds got within a few false alarms of the model, so a rule is the baseline to beat, not a strawman.
  • One search window. The query finds only loops with transfers between 3,000 and 10,000, and three or four accounts. Rings outside that window are not candidates.

Gotchas

These cost us the most time, and they are worth knowing about before you run the notebooks:

  • Password login can be blocked. Newer Snowflake accounts reject single-factor password login with an "incorrect username or password" error even when the password is right. Set up key-pair login and set SNOWFLAKE_PRIVATE_KEY_PATH. A relative path works if the key file sits next to the notebook.
  • The role that creates the database owns it. Objects created by ACCOUNTADMIN are not usable by SYSADMIN. Use one role (such as SYSADMIN) for both notebooks, and a new database name, rather than a pre-existing database owned by another role.
  • Replacing tables is guarded. The generator never drops a table by default. REPLACE_TABLES_IN must match the target exactly, and the notebook checks that the role can create tables before it replaces anything. We added this after an earlier version dropped tables before discovering it lacked the privilege to recreate them.
  • Timestamp parsing. TRY_TO_TIMESTAMP_NTZ accepts text only. The triage query wraps the column in TO_VARCHAR so it works whether the column is text or a real timestamp.
  • Replay files are tied to the question and the sample. They are keyed by loop and question, so if you change the guidance or the sample, the saved answers are stale. Delete the replay file and record a new one. Each dataset has its own replay file, so the two datasets do not clash.
  • Stops are quiet. When a notebook stops deliberately (e.g., because the tables already exist), it prints a message instead of an error warning. Real failures, such as missing privileges, still raise errors.
  • Leave REPLACE_TABLES_IN as None. Set it only for the run that needs it, then set it back.

Summary

We built a small Snowflake experiment around one question: when you ask a model whether a loop of payments is a fraud ring, how much would it help to tell the model what to look for? On a synthetic dataset with decoys and hard cases, the bare question caught nearly every real ring but raised 14 false alarms. The guided question kept the recall and cut the false alarms to 2. On a second dataset, with a different seed and shifted ranges, the same guidance gave 0.929 precision and 0.963 recall.

A well-chosen rule is a serious competitor. The amounts and risk rule was the most precise method on both datasets, and the guided model beat it only on recall and its ability to send mixed cases to a person. The model's value here is not that it replaces a rule. It's that it handles the cases cut-off rules miss, once you tell it what matters.

The practical lesson is to treat the guidance as part of the system. Test it on a dataset you did not tune it on. Check that the sample shows the hard cases. Read the thresholds as carefully as the code. A missed ring and a needless review do not cost the same, and the right method depends on which one you can afford.

The full source code is available on GitHub.

Language model jupyter notebook sql

Opinions expressed by DZone contributors are their own.

Related

  • First Native LLM Fine-Tuned for the Telecom Industry
  • Idempotent Consumers: Preventing Stale Retries With Version-Fenced Writes
  • MySQL Instant DDL: Metadata Locks, Waiting Writers, and Query Pileups
  • Taming Parameter Sniffing in SQL Server 2022 With PSP Optimization

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook