Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/resolution.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ the first signal that fires:
| Signal | Confidence | Reason |
|--------|------------|--------|
| The candidate's id equals the entity's id. | 1.0 | `id` |
| The candidate and the entity share an external id key with the same value. | 1.0 | `external_id` |
| The candidate and the entity share an external id key with the same value. Keys and values are never blank: inserts, `create`, and `update` reject them. | 1.0 | `external_id` |
| Any of the candidate's name and aliases matches the entity's name or one of its aliases, after NFC normalization and case folding. | 0.95 | `alias` |
| Same type, and the lexical similarity of the names reaches `threshold`. Only with `fuzzy=True`. | the score | `similarity` |

Expand Down
2 changes: 1 addition & 1 deletion docs/resources.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ raises `ValidationError`.
| `type` | May change only case or spacing, since the type is part of the id. Any other type raises `ValidationError`. The stored type is kept, so `type="person"` on a `Person` is a no-op, unless the new type is a schema type name or alias, which stores the schema's type name. |
| `aliases`, `remove_aliases` | Add or remove aliases. |
| `properties`, `remove_properties` | Merge into or remove from the stored properties. |
| `external_ids` | Merges into the stored external ids. |
| `external_ids` | Merges into the stored external ids. A blank key or value raises `ValidationError`. |

Aliases are cleaned like names (trimmed, NFC-normalized) before they are stored
or compared, so `" Other"` is stored as `Other`. `remove_aliases` is cleaned the
Expand Down
6 changes: 4 additions & 2 deletions src/selfgraph/_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,18 +471,20 @@ def _merge_props(


def _require_str_mapping(name: str, value: Any) -> None:
"""Validate a value is a mapping of strings to strings.
"""Validate a value is a mapping of nonblank strings to nonblank strings.

@param name (str): the field name for the error message.
@param value (Any): the value to check.
@return (None): nothing; raises ValidationError when not a string-to-string mapping.
@return (None): nothing; raises ValidationError when not a string-to-string mapping or a key or value is blank.
"""
_require_mapping(name, value)
for key, item in value.items():
if not key.strip():
raise ValidationError(f"{name} keys cannot be empty or whitespace", field=name)
if not isinstance(item, str):
raise ValidationError(f"{name} must map strings to strings")
if not item.strip():
raise ValidationError(f"{name} values cannot be empty or whitespace", field=name)


def _require_clean_evidence(ev: EvidenceInput) -> None:
Expand Down
18 changes: 18 additions & 0 deletions tests/test_entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,24 @@ def test_create_get_update_delete():
run(g.entities.delete(e.id))


def test_a_blank_external_id_value_is_rejected_so_unrelated_entities_never_merge():
g = fresh_graph("blank_xid")
ann = run(g.entities.create("Ann Lee", "Person"))
for bad in ({"crm": ""}, {"crm": " "}):
bob = {"name": "Bob Stone", "type": "Person", "external_ids": bad}
for call in (
lambda bad=bad: g.entities.create("Bob Stone", "Person", external_ids=bad),
lambda bad=bad: g.entities.update(ann.id, external_ids=bad),
lambda bob=bob: g.insert.facts({"entities": [bob]}),
):
with pytest.raises(ValidationError, match="^external_ids values cannot be empty or whitespace$") as err:
run(call())
assert (err.value.code, err.value.field) == ("invalid_argument", "external_ids")
stored = run(g.entities.list()).items
assert [(e.id, e.aliases, e.external_ids) for e in stored] == [(ann.id, [], {})]
assert run(g.entities.merges(ann.id)).items == []


def test_list_filters_and_pagination():
g = new_graph()
for i in range(3):
Expand Down
3 changes: 2 additions & 1 deletion typescript/src/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ export function requireJsonMapping(name: string, value: unknown, safeInts = true
}

/**
* Validate a value is a mapping from strings to strings.
* Validate a value is a mapping from nonblank strings to nonblank strings.
*
* @param name (string): the field name for the error message.
* @param value (unknown): the value.
Expand All @@ -446,5 +446,6 @@ export function requireStrMapping(name: string, value: unknown): asserts value i
for (const [key, item] of Object.entries(value)) {
if (!pyStrip(key)) throw new ValidationError(`${name} keys cannot be empty or whitespace`, { field: name });
if (typeof item !== "string") throw new ValidationError(`${name} must map strings to strings`);
if (!pyStrip(item)) throw new ValidationError(`${name} values cannot be empty or whitespace`, { field: name });
}
}
13 changes: 13 additions & 0 deletions typescript/test/conformance/py_side.py
Original file line number Diff line number Diff line change
Expand Up @@ -1770,6 +1770,19 @@ async def write(graph):
except ValidationError as exc:
out["facts_none"] = str(exc)
out["mcp_arguments"] = await mcp_argument_errors()
out["external_id_errors"] = []
for bad in ({"crm": ""}, {"crm": " \t"}):
for call in (
lambda bad=bad: graph.entities.create("Blank Id", "Person", external_ids=bad),
lambda bad=bad: graph.insert.facts(
{"entities": [{"name": "Blank Id", "type": "Person", "external_ids": bad}]}
),
):
try:
await call()
out["external_id_errors"].append("accepted")
except ValidationError as exc:
out["external_id_errors"].append([exc.code, exc.field, str(exc)])
out["flag_errors"] = []
for flag in ("false", 0):
for call in (
Expand Down
16 changes: 16 additions & 0 deletions typescript/test/conformance/ts_side.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2132,6 +2132,22 @@ export async function write(graph: SelfGraph): Promise<Record<string, unknown>>
out.facts_none = exc.message;
}
out.mcp_arguments = await mcpArgumentErrors();
const externalIdErrors: unknown[] = [];
for (const bad of [{ crm: "" }, { crm: " \t" }]) {
for (const call of [
() => graph.entities.create("Blank Id", "Person", { external_ids: bad }),
() => graph.insert.facts({ entities: [{ name: "Blank Id", type: "Person", external_ids: bad }] }),
]) {
try {
await call();
externalIdErrors.push("accepted");
} catch (exc) {
if (!(exc instanceof ValidationError)) throw exc;
externalIdErrors.push([exc.code, exc.field, exc.message]);
}
}
}
out.external_id_errors = externalIdErrors;
const flagErrors: string[] = [];
for (const flag of ["false", 0]) {
for (const call of [
Expand Down
21 changes: 21 additions & 0 deletions typescript/test/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,27 @@ function suite(spec: StoreSpec) {
const ns = uniqueNs(`ts_${spec.name}`);
const fresh = freshGraphs(spec, "fresh");

it("rejects a blank external id value so unrelated entities never merge", async () => {
const g = fresh();
const ann = await g.entities.create("Ann Lee", "Person");
for (const bad of [{ crm: "" }, { crm: " " }]) {
for (const call of [
() => g.entities.create("Bob Stone", "Person", { external_ids: bad }),
() => g.entities.update(ann.id, { external_ids: bad }),
() => g.insert.facts({ entities: [{ name: "Bob Stone", type: "Person", external_ids: bad }] }),
]) {
await expect(call()).rejects.toMatchObject({
message: "external_ids values cannot be empty or whitespace",
code: "invalid_argument",
field: "external_ids",
});
}
}
const stored = (await g.entities.list()).items.map((e) => [e.id, e.aliases, e.external_ids]);
expect(stored).toEqual([[ann.id, [], {}]]);
expect((await g.entities.merges(ann.id)).items).toEqual([]);
});

it("rejects proto properties from a custom extractor", async () => {
const g = fresh({
extractor: {
Expand Down
Loading