r/SQLv2 • • 3d ago

SQLv2 Lesson 9: similar isn't the same item. A white mouse scores 0.85 against your black one, the real mouse line only 0.49. One contradiction check in the JOIN catches it and 3 more look-alikes (beginner, real output)

Lesson 9 of the beginner series, run on SynapCores 2.5.1 this morning. (This sub is run by the SynapCores team.)

Lesson 8 homework, answered: 'Wireless mouse, white' matches 'Wireless mouse, black' at 0.85, higher than all 7 real matches on that invoice (the real mouse line: 0.49). Full output under Lesson 8.

Similarity asks: same kind of thing? A white and a black mouse are. To book stock or check prices, you need: same item?

Step 1: next week's invoice

Lesson 8's tables plus 5 new supplier lines (lines 9 to 13; INSERTs in the first comment). You stock the black mouse, 2 m cable, 65 W charger, US-layout keyboard and aluminium stand.

Lesson 8's JOIN matches all five, at 0.85 to 0.94. Four are wrong, and no threshold can split them off: real matches sit both below (0.49 to 0.72) and above (the stand, 0.94).

Step 2: a different question

NLI (natural language inference) is a small model in the engine that scores whether one text contradicts another:

SELECT ROUND(JSON_EXTRACT(NLI_CLASSIFY('nli-default',
  'Wireless mouse, black', 'Wireless mouse, white'), '$.scores.contradiction'), 3);

0.998

The real mouse line, 'Cordless optical mouse, blk': 0.018.

Step 3: both checks in one query

WITH best AS (... same as Lesson 8 ...),
checked AS (
  SELECT i.line, b.id, i.item, c.name, b.sim,
    JSON_EXTRACT(NLI_CLASSIFY('nli-default', c.name, i.item), '$.scores.contradiction') AS c1,
    JSON_EXTRACT(NLI_CLASSIFY('nli-default', i.item, c.name), '$.scores.contradiction') AS c2
  FROM best b JOIN invoice_lines i ON i.line = b.line JOIN catalog c ON c.id = b.id
  WHERE b.rn = 1)
SELECT line, item, ROUND(sim, 2) AS sim, ROUND(c1, 2) AS c1, ROUND(c2, 2) AS c2,
  CASE WHEN sim < 0.43 THEN 'NO MATCH: ask purchasing'
       WHEN c1 > 0.5 AND c2 > 0.5 THEN 'DIFFERENT ITEM: ask purchasing'
       ELSE name END AS matched
FROM checked ORDER BY line;

1  Type-C power adapter 65W for notebooks  0.72 0.00 0.05  USB-C laptop charger, 65 W
2  Cordless optical mouse, blk  0.49 0.02 0.00  Wireless mouse, black
3  2m high speed HDMI lead  0.64 0.00 0.01  HDMI cable, 2 m
4  UHD 27in display  0.60 0.00 0.00  27-inch 4K monitor
5  Keyboard w/ mechanical switches, ANSI  0.63 0.01 0.99  Mechanical keyboard, US layout
6  Ergonomic mesh office chair  0.37 1.00 1.00  NO MATCH: ask purchasing
7  ANC headphones with boom mic  0.50 0.61 0.03  Noise-cancelling headset with microphone
8  Dock, USB-C, 2x HDMI out  0.70 0.00 0.00  USB-C docking station, dual display
9  Wireless mouse, white  0.85 1.00 1.00  DIFFERENT ITEM: ask purchasing
10  HDMI cable, 5 m  0.92 1.00 1.00  DIFFERENT ITEM: ask purchasing
11  USB-C laptop charger, 100 W  0.90 1.00 1.00  DIFFERENT ITEM: ask purchasing
12  Mechanical keyboard, UK layout  0.85 1.00 1.00  DIFFERENT ITEM: ask purchasing
13  Laptop stand, aluminum  0.94 0.00 0.00  Aluminium laptop stand

Why both ways? NLI takes the first text as given and checks the second against it, so a pair can clash one way only (lines 5 and 7). Each wrong item clashes both ways (9 to 12). Requiring both keeps all 8 real matches.

Step 4, the payoff: Lesson 8's price check

On the new invoice: $429 over list.

USB-C laptop charger, 100 W  10 x 59.00 vs 39.00  +200.00
UHD 27in display  4 x 315.00 vs 289.00  +104.00
HDMI cable, 5 m  20 x 14.00 vs 9.00  +100.00
Type-C power adapter 65W for notebooks  10 x 41.50 vs 39.00  +25.00

$300 of that is the 100 W charger and the 5 m cable, priced as your 65 W charger and 2 m cable. Run it on checked k with AND NOT (k.c1 > 0.5 AND k.c2 > 0.5) and it's Lesson 8's $129 again. The white mouse and UK keyboard are at list price, so only Step 3 stops them being booked as the black mouse and US keyboard.

Homework

The supplier sends 'Wireless mouse', no colour, 10 at 19.00.

  1. Which product does the JOIN pick, and at what similarity?
  2. Does the contradiction check flag it?
  3. Should it? What would you do with a line that leaves a detail out?

Reply with your guesses and I'll post the real output.

Free Community Edition: https://synapcores.com/download?utm_source=reddit&utm_medium=owned&utm_campaign=sqlv2-lesson-9

What's the worst look-alike that got past your matching: wrong size, colour, wattage?

1 Upvotes

2 comments sorted by

1

u/Alternative_Pin9598 3d ago

Already have Lesson 8's tables? Add next week's 5 lines and their vectors (the DELETE first clears line 9 if you kept it from Lesson 8's homework):

DELETE FROM invoice_lines WHERE line > 8;
INSERT INTO invoice_lines (line, item, qty, unit_price) VALUES
  (9, 'Wireless mouse, white', 10, 19.00), (10, 'HDMI cable, 5 m', 20, 14.00),
  (11, 'USB-C laptop charger, 100 W', 10, 59.00),
  (12, 'Mechanical keyboard, UK layout', 6, 79.00), (13, 'Laptop stand, aluminum', 5, 35.00);
UPDATE invoice_lines SET vec = EMBED(item) WHERE line > 8;

With these tables the script below works too: skip setup.

Starting fresh? The full script (Python, standard library only) is in the reply below. python3 lesson9.py setup creates both tables with all 13 lines and their vectors; match runs Lesson 8's query, check Step 3, prices Step 4 (before and after), and cleanup drops everything.

NLI is a one-time opt-in: synapcores pull nli-default, then synapcores models enable-nli nli-default, both with the --config your server uses, then restart the server.

Ran it twice from scratch on 2.5.1: same scores, same result.

Same two signals, different job: Recipe of the week #2 on r/synapcores uses similarity + NLI to catch new facts that contradict an AI agent's memory before they're saved: https://www.reddit.com/r/synapcores/comments/1xru0wg/

New to SynapCores? Install steps and the 5 recipes to try first: https://www.reddit.com/r/synapcores/comments/1xfxqej/

1

u/Alternative_Pin9598 3d ago

lesson9.py (set SC_URL and SC_TOKEN; run setup, then match, check, prices; cleanup when done):

import json, os, sys, urllib.request, urllib.error
URL = os.environ.get("SC_URL", "http://localhost:8080")
TOK = os.environ["SC_TOKEN"]

def sql(q, ok_fail=False):
    req = urllib.request.Request(URL + "/v1/query/execute", method="POST",
        data=json.dumps({"sql": q, "database": "main"}).encode(),
        headers={"Authorization": "Bearer " + TOK, "content-type": "application/json"})
    try:
        return json.load(urllib.request.urlopen(req, timeout=300))["data"]
    except urllib.error.HTTPError as e:
        if ok_fail: return None
        raise SystemExit(f"{e.code}: {e.read()[:400]}")

CATALOG = [(101, "USB-C laptop charger, 65 W", 39.00), (102, "Wireless mouse, black", 19.00),
           (103, "HDMI cable, 2 m", 9.00), (104, "27-inch 4K monitor", 289.00),
           (105, "Mechanical keyboard, US layout", 79.00), (106, "USB-C docking station, dual display", 129.00),
           (107, "Noise-cancelling headset with microphone", 99.00), (108, "Aluminium laptop stand", 35.00)]
INVOICE = [(1, "Type-C power adapter 65W for notebooks", 10, 41.50), (2, "Cordless optical mouse, blk", 20, 19.00),
           (3, "2m high speed HDMI lead", 50, 9.00), (4, "UHD 27in display", 4, 315.00),
           (5, "Keyboard w/ mechanical switches, ANSI", 6, 79.00), (6, "Ergonomic mesh office chair", 2, 240.00),
           (7, "ANC headphones with boom mic", 8, 99.00), (8, "Dock, USB-C, 2x HDMI out", 5, 129.00)]
# next week's invoice adds 5 lines
NEW = [(9, "Wireless mouse, white", 10, 19.00), (10, "HDMI cable, 5 m", 20, 14.00),
       (11, "USB-C laptop charger, 100 W", 10, 59.00), (12, "Mechanical keyboard, UK layout", 6, 79.00),
       (13, "Laptop stand, aluminum", 5, 35.00)]

BEST = """WITH best AS (
  SELECT i.line, c.id, COSINE_SIMILARITY(i.vec, c.vec) AS sim,
    ROW_NUMBER() OVER (PARTITION BY i.line ORDER BY COSINE_SIMILARITY(i.vec, c.vec) DESC) AS rn
  FROM invoice_lines i CROSS JOIN catalog c)
"""
# Lesson 8's query, unchanged
MATCH = BEST + """SELECT i.line, i.item, ROUND(b.sim, 2) AS sim,
  CASE WHEN b.sim >= 0.43 THEN c.name ELSE 'NO MATCH: ask purchasing' END AS matched
FROM best b JOIN invoice_lines i ON i.line = b.line JOIN catalog c ON c.id = b.id
WHERE b.rn = 1 ORDER BY i.line"""
# Lesson 9: the same best match, plus a contradiction check read both ways
CHECKED = BEST + """, checked AS (
  SELECT i.line, b.id, i.item, c.name, b.sim,
    JSON_EXTRACT(NLI_CLASSIFY('nli-default', c.name, i.item), '$.scores.contradiction') AS c1,
    JSON_EXTRACT(NLI_CLASSIFY('nli-default', i.item, c.name), '$.scores.contradiction') AS c2
  FROM best b JOIN invoice_lines i ON i.line = b.line JOIN catalog c ON c.id = b.id
  WHERE b.rn = 1)
"""
CHECK = CHECKED + """SELECT line, item, ROUND(sim, 2) AS sim, ROUND(c1, 2) AS c1, ROUND(c2, 2) AS c2,
  CASE WHEN sim < 0.43 THEN 'NO MATCH: ask purchasing'
       WHEN c1 > 0.5 AND c2 > 0.5 THEN 'DIFFERENT ITEM: ask purchasing'
       ELSE name END AS matched
FROM checked ORDER BY line"""
# Lesson 8's price check, before and after the check
PRICES_L8 = BEST + """SELECT i.item, c.name, i.qty, i.unit_price, c.list_price,
  (i.unit_price - c.list_price) * i.qty AS over_list
FROM best b JOIN invoice_lines i ON i.line = b.line JOIN catalog c ON c.id = b.id
WHERE b.rn = 1 AND b.sim >= 0.43 AND i.unit_price > c.list_price
ORDER BY over_list DESC"""
PRICES = CHECKED + """SELECT i.item, c.name, i.qty, i.unit_price, c.list_price,
  (i.unit_price - c.list_price) * i.qty AS over_list
FROM checked k JOIN invoice_lines i ON i.line = k.line JOIN catalog c ON c.id = k.id
WHERE k.sim >= 0.43 AND NOT (k.c1 > 0.5 AND k.c2 > 0.5) AND i.unit_price > c.list_price
ORDER BY over_list DESC"""

def rows(q):
    return sql(q)["rows"]

cmd = sys.argv[1]
if cmd == "setup":
    sql("CREATE TABLE catalog (id INTEGER PRIMARY KEY, name TEXT, list_price FLOAT, vec VECTOR(384))")
    sql("CREATE TABLE invoice_lines (line INTEGER PRIMARY KEY, item TEXT, qty INTEGER, unit_price FLOAT, vec VECTOR(384))")
    sql("INSERT INTO catalog (id, name, list_price) VALUES " +
        ", ".join(f"({i}, '{n}', {p:.2f})" for i, n, p in CATALOG))
    sql("INSERT INTO invoice_lines (line, item, qty, unit_price) VALUES " +
        ", ".join(f"({l}, '{t}', {q}, {p:.2f})" for l, t, q, p in INVOICE + NEW))
    sql("UPDATE catalog SET vec = EMBED(name)")
    sql("UPDATE invoice_lines SET vec = EMBED(item)")
    print("catalog:", rows("SELECT COUNT(*) FROM catalog")[0][0], "invoice lines:", rows("SELECT COUNT(*) FROM invoice_lines")[0][0])
elif cmd == "match":
    for r in rows(MATCH): print(r)
elif cmd == "check":
    for r in rows(CHECK): print(r)
elif cmd == "prices":
    before = rows(PRICES_L8)
    print("Lesson 8 price check:")
    for r in before: print(r)
    print("over list:", sum(r[5] for r in before))
    after = rows(PRICES)
    print("with the contradiction check:")
    for r in after: print(r)
    print("over list:", sum(r[5] for r in after))
elif cmd == "cleanup":
    sql("DROP TABLE invoice_lines", True); sql("DROP TABLE catalog", True)