Skip to main content

One filter, one meaning

· 23 min read
Matej Škvarč
Andromeda Maintainer

Take a Vehicle whose speed is 80. Before v1.1.0, if you subscribed to Vehicles with q=speed.value==80, Andromeda notified you about it. If you sent Query Entities the same q, it told you no Vehicle matched. Some of the four other brokers I tried give the same two answers.

Query Entities was right. Clause 4.9 of NGSI-LD v1.9.1 (ETSI GS CIM 009) says every name after the first in an attribute path "represents a (sub)Property or (sub)Relationship". A Property's value is neither, so speed.value asks for a sub-Property called value, and the Vehicle doesn't have one. The q that tests the value is plain speed==80.

The bug came from Andromeda evaluating each filter in three places, with separate code in each deciding what a term means. v1.1.0 replaces that code with one description of what the filter means, which all three places use.

Why a filter is evaluated in three places​

The first place is SQL over the rows Andromeda stores for each attribute instance, which answers Query Entities and the Temporal API. Subscriptions can't work like that. Every time a write changes an Entity, the broker has to work out which Subscriptions to notify, and going to the database once per Subscription would turn one write to a type with 10,000 Subscriptions into 10,000 statements. So the second place is memory, where a Subscription is checked against the Entity the write just produced. The third is csf, the filter over Context Source Registrations. Discovery runs it in SQL against the stored registration documents, and a Context Source Registration Subscription checks it with the same in-memory matcher.

All three already used the same parser and the same syntax tree, so they never disagreed about how to read a filter. They disagreed about what a term looks at once it's parsed, such as a value of another data type, an element that isn't there, or an attribute holding several values. Each place answered those questions in its own code, so each could answer them differently. The rule that a Relationship only supports == and != existed in three copies. The rule that a value of another data type counts as "unequal" was written out five separate times in the SQL code alone.

Three ways to disagree​

Before I changed any code, I went through every clause the query engine depends on, compared it with what the code did, and turned each suspected difference into a test. The differences fell into three groups, and each group needed a different fix.

The database and the in-memory matcher disagree​

Take two Diary Entities that both hold d as "2024-01-15". One declares it an NGSI-LD Date through valueType, the other doesn't. With q=d~="2024.*", Query Entities returned both, while a Subscription matched only the undeclared one. Andromeda keeps a Date in the same text column as a String, and the SQL for a pattern never checked which of the two it was looking at. Clause 4.6.3 lists Date as a data type of its own, and clause 4.5.2.2 makes valueType "a non-reified alternative to the use of a native JSON-LD @type for the Property value", so I treat the declared value as a Date, not a String. Clause 4.9 says of patterns, "If the target value data type is different than String then it shall be considered as not matching." So this time the Subscription was right.

With speed.value it was the other way round. Each side was wrong at least once, so neither could be the reference for the other.

The grammar and its own example disagree​

A Linked Entity query follows a Relationship to another Entity and tests an attribute there. EXAMPLE 13 in clause 4.9 writes sensor{humidity}==40. EXAMPLE 14 adds the type of the Entity at the other end, as in sensor{Device:humidity}==40, and the clause presents it as a hint for a faster lookup. The grammar in the same clause can't read EXAMPLE 14.

LinkedEntityPath = *1(EntityType 1*(%x2C EntityType) %x3A) AttrName %x7B LinkedEntityPath %x7D
LinkedEntityPath =/ ValuePath

It allows a list of types only with at least two types, and only before a further hop. Names can't hold a colon either, so Device:humidity isn't one name. A hop can carry no type, one type or several, and it can end the path or lead to a further hop. Of those six shapes the grammar accepts three, and EXAMPLE 14's isn't one of them.

A further hopThe path ends
No typesa{b{c}}accepteda{b}, see the note under the tableaccepted
One typea{T:b{c}}refuseda{T:b}, see the note under the tablerefused
Two or more typesa{T1,T2:b{c}}accepteda{T1,T2:b}refused
How the grammar in clause 4.9 reads a hop, with and without a list of types.
EXAMPLE 13 in clause 4.9 writes this shape.
EXAMPLE 14 in clause 4.9 writes this shape.

The clause gives no reason for either limit, and its prose asks for "the required Entity Type", in the singular. Both limits look like slips, so Andromeda applies the rule with them corrected. The corrected rule accepts all six shapes, and the three the printed rule accepts keep their meaning.

LinkedEntityPath = *1(EntityType *(%x2C EntityType) %x3A) (AttrName %x7B LinkedEntityPath %x7D / ValuePath)

I could be wrong about the slips. If the limits are deliberate, Andromeda accepts the three shapes the table marks as refused, and it shouldn't. A query that has to stay inside the printed grammar uses no type, or two or more types before a further hop, as in a{T1,T2:b{c}}.

Andromeda treats the types as a filter, so sensor{Device:humidity}==40 skips a sensor that points at a Thermometer. The clause calls them a hint for a faster lookup, but I read everything else it says about them as a restriction. It speaks of "the required Entity Type" and says "only such NGSI-LD Entities need to be considered". And if the types are only a hint, what should the answer be? Should a station whose sensor points at a Thermometer with a humidity of 40 be selected or not? I can't see how a hint decides that, and a broker that uses it and one that ignores it would answer differently. Nothing else in q can test the type stored on a linked Entity, either.

Splitting Device:humidity at the colon works because no name in the grammar holds one, so the colon after Device can only end the list. AttrName hasn't allowed a colon in any version of the grammar from 1.1.1 on.

A name in q can be a term of the @context, a prefixed name such as schema:location, or an absolute IRI, and a broker has to be able to write the last two. When it gives a Subscription back, it renders a name no term abbreviates as its full IRI (clause 5.5.7). When it forwards a query, it compacts the names into compact IRIs (clause 4.3.6.6), and other brokers read those without quotes. So Andromeda reads a prefixed name or an IRI as it is, as in ex:speed>50, or in the grammar's own quotedStr, whose value is the name, as in "ex:speed">50. The quotes only delimit, so both expand through the prefix ex and select the same Entities. The start of a hop's braces is the one place where I didn't let a colon belong to a name. A type list has no other spelling, while a name there can go in quotes or be replaced by a term, so the colon ends the list and sensor{ex:humidity} reads ex as a type. A prefixed attribute there is written sensor{"ex:humidity"}, and an IRI holding a dot is always quoted, since a dot starts a sub-attribute. Everywhere else, Andromeda writes a name back without quotes when it reads back as the same name. v1.0.0 also read names without quotes, but it wrote a name holding a ; or a , the same way, so a stored IRI holding one read back as another filter.

The database and the in-memory matcher share the parser, so they always agreed on hops and names, and only the text could tell me whether they were right.

The query steps and an annex example disagree​

For the Temporal API, clause 5.7.4.4 checks a q against "the Attribute instances resulting from the initial filtering performed by the temporal query", the instances whose timestamp lies inside the window (clause 4.11). A term on an attribute with no instance there matches nothing, != included, because a matching Entity "shall contain the target element" (clause 4.9).

Annex C.5.5 asks for Vehicles whose brandName isn't "Mercedes" between noon and one o'clock on 1 August 2018. It notes that brandName "does not have any temporal evolution", yet it still returns a Vehicle, which only works if the filter reads a brandName from outside the window.

Andromeda used to do what the annex does. Now it follows the steps, so a brandName that never changes can't select anything in a temporal query. I chose the steps for what they say, and because as I read it the rest of the clause works the same way.

The steps are normative, and they say the q "shall be checked against" the instances the temporal query kept. Annex C is informative, so its example can't overrule them.

Every other step of the clause works inside the window too. An Entity with no data in the window is removed before the q runs. The geoquery is checked against "the GeoProperty instances that are within the interval defined by the temporal query", lastN counts the timestamps "within the concerned temporal interval", and the last step keeps only the instances that meet the restrictions. Clause 4.18 says that for the Temporal Evolution "a given Scope is considered valid from the time it has been set until the time it has been explicitly removed". I take that to mean only a Scope is carried into the window, since the sentence wouldn't be needed if every attribute were. Reading today's value instead would test a window in 2018 against today's data.

The same clause decides which instances come back. Its last step keeps "only the Attribute instances ... which meet the temporal, query and geoquery restrictions", without saying how a filter for a whole Entity applies to one instance. I apply it to each instance on its own, the way the temporal restriction in the same list applies. With the annex's speeds of 120, 80 and 100, q=speed>90 returns 120 and 100, and a geoquery narrows its GeoProperty the same way.

Two test cases in ETSI's conformance suite assume the opposite and remove nothing. 021_08_01 asks for Vehicles with q=speed>90 and expects a speed of 80 back. 021_09_01 asks for Vehicles within 2 km of a point and expects a location about 900 km away back as well. Both still do on the suite's develop branch at commit 7069f560. Andromeda's versions of the two tests expect those instances to be left out.

How I decided​

The specification contradicts itself in places, so no broker can follow every sentence of it. Its grammar refuses its own EXAMPLE 14, an annex example answers a temporal query differently from the steps it illustrates, and the clause that limits a path to short-hand names sits beside clauses that make a broker write full IRIs into one. For each of these I had to choose which part of the text to keep.

Andromeda may accept more ways of writing a query than the grammar does, but a query the grammar already accepts keeps the answer I read in the text. The spaces and nested parentheses the examples use are fine by that rule, since they don't change what a query selects, and so is EXAMPLE 14's single type in a hop. Annex C.5.5 isn't, because it changes the answer to a query that was valid all along. EXAMPLE 12 writes gender==Male without quotes, and Andromeda refuses that. The grammar only has quoted strings, and if Andromeda read a bare word as one, a typo such as active==ture would quietly match nothing instead of failing with a 400. Written gender=="Male", it gives the answer the example shows.

When parts of the text disagree, I go with the reading most of it supports, and I assume every feature is meant to work. Requiring two types, and only before a further hop, struck me as odd, and the text gives no reason for it. The prose and EXAMPLE 14 both use one type, so I read the limits as slips. Names were the opposite case, where the rest of the text asks for more than the grammar can spell. Two clauses make a broker write full and compact IRIs into a q it gives back or forwards, so Andromeda reads them, with quotes or without. Only at the start of a hop's braces does the colon keep the grammar's meaning, because a type list has no other way to be written.

The temporal window was in the end a judgement. Annex C.5.5 reads brandName from outside the window, and two tests in ETSI's conformance suite keep instances that fail the filter. Narrowing to the window made more sense to me, and the steps back it with a "shall", as does every other step of the clause. Where the text leaves a question open, as with which temporal instances come back, I make the same kind of call, write it down on the query language page and pin it with a test.

I also look at what the other brokers do, because clients written for them send Andromeda the same queries. Where they all behave the same way, I follow them, unless I read the text differently or their reading makes less sense to me. They all read an unquoted prefixed name, so Andromeda reads one too, everywhere except at the start of a hop's braces. Hops are where I didn't follow them, because the way I read the text, the types in a hop are a filter.

One description of what a filter means​

Andromeda now parses a filter and turns it, once, into a plain description of what it means, rewritten into one standard shape, and the evaluators keep no decisions of their own. That description is an ordinary value that can be printed and compared, and it knows nothing about databases or about how Entities are modelled. For each term, it records the answer for every kind of value an attribute can hold. The SQL over attribute rows, the SQL over registration documents and the in-memory matcher all take their answers from it, and each of them only supplies where the data lives and how the answer is written out, as SQL or as a check in memory.

The standard shape also gives every query a single fingerprint. q=a==1;b==2 and q=b==2;a==1 are the same filter, so a cursor from one keeps working with the other, and both prepare the same SQL statement. Given 32 different spellings of 8 filters, the SQL code used to produce 27 different conditions, and it now produces 8.

Tests that can tell the two sides apart​

The new description only helps if it gives the answers the old code gave, apart from the bugs I meant to fix. While the old in-memory evaluator still existed, I ran the two side by side over the 19 Entities of the hand-written test set, plus two more built to be awkward. Those two had nested arrays, several strings per language, a Relationship pointing at several objects, an attribute with several instances and a not-a-number. Old and new agreed on all 235,200 single terms of a grid, on 50,000 randomly generated terms and on 5,000 generated filters.

Of the 235,200 terms, 228,069 matched no Entity, none matched every Entity, and only 7,131 matched some Entities and not others. Two evaluators that agree a filter matches nothing tell you very little about either, so only those 7,131 terms could show a difference between them.

The black-box test suite had the same problem. It has a generated test that creates Entities, gives Query Entities and a Subscription the same filter, and expects both to pick the same Entities. When I first measured it, only 482 of its 1,920 q filters, 25.1%, matched anything at all. Its operands came from fixed lists rather than from the values the Entities actually held, so most terms never had a chance to match.

The test now has to stay within four limits. It checks them twice, once after the Entities are created and again after a second write changes each one, adding up the results across all its fixed seeds. If a run misses a limit, it fails and reports the value it measured. In each pair below, the first figure is from after creation and the second from after the change.

  • At least 65% of the filters match at least one Entity.

    The q test measured 78.0% and 80.4%, the geo test 73.2% and 74.3%.

  • Among the filters that match any, the median matches at least 3 Entities for q and 2 for geo.

    It was 3 and 4 for q, and 2 for geo after both writes.

  • At most 10% of the filters match every Entity.

    The q test measured 0.0% and 0.1%, the geo test 0.5% and 1.6%.

  • At most 5% of the answers with two or more Entities repeat the exact set of an earlier filter of the same seed.

    The q test measured 2.7% and 2.8%, the geo test 1.9% and 2.1%.

The q test uses 64 seeds, each with 20 Entities and 30 filters, so 1,920 filters per round, and no seed has two identical filters. Across all seeds, 1,911 of the 1,920 filter texts are different. The geo test uses 32 seeds, each with 12 Entities and 24 geo-queries. These figures come from a run of the 1.1.0 code.

To get there I changed the generator and left the limits alone. Each filter is now built around one Entity and takes most of its terms from that Entity's values, flipping the operator now and then. Each attribute name usually belongs to one attribute family, so a range or an ordering has a chance to match a second Entity. A range or an ordering never lets through every value of the pool it's drawn from, and the geo test's set of shapes grew from 15 geometries to 33, spread over 16 regions.

A filter made from one Entity's values tends to match exactly that Entity, and a limit on "matches something" can't tell. The median limit stops the test from asking, filter after filter, only whether one particular Entity matches. The repeat limit does the same for filters that keep finding the same group of Entities.

Earlier, looser versions of this test found disagreements the hand-written cases had missed, such as rl!=1..5 on a ListRelationship, which Query Entities matched and a Subscription didn't. The stricter version hasn't found any. Under the limits, finding nothing means the two sides agree on filters that select some Entities and not others.

Checks against later changes​

Three more checks look for a later change that would split the meaning again.

The first is a snapshot of the shared description itself. For every operator and every kind of value, it prints the answer. Where no clause gives the answer and Andromeda had to decide, the snapshot marks it as a ruling.

The attribute holdsx==5x!=5
A numberequals 5doesn't equal 5
NaN, INF or -INF, a rulingneveralways
A stringneveralways
An array of valuessome element equals 5no element equals 5
Part of the snapshot. A green answer always matches, a grey one never does, and a blue one depends on the value.
No clause covers this row. Numbers beyond the decimals follow XSD.

JSON has no NaN or infinity, but a Property can hold "NaN", "INF" or "-INF" declared as xsd:double or xsd:float, and XSD counts those as numbers. Clause 4.9 says how numbers compare but not what these do, so that row is a ruling. If a change made NaN equal to 5, that row of the snapshot would change, and the change would show up in review as one diff instead of as a failing test somewhere further down.

The second check is an architecture test, which stops anyone adding an evaluator with its own idea of what a filter means. It parses every production source file in the workspace and fails if any code pattern-matches on the variants of a term's syntax tree. Only the module that parses filters and builds their description may. Calling an accessor or building a term is still allowed, since neither decides what a term means.

The third covers the SQL. About 1,380 assertions used to check that a generated statement contained a certain fragment. A check like that keeps passing when a refactor adds an extra condition right next to the fragment. Nearly all of those tests now snapshot the whole statement and its bound values. None of them checks which plan PostgreSQL chooses, since that depends on statistics and would make the tests flaky, so performance is left to the benchmarks. csf and geo-queries have their own side-by-side tests as well.

What clients notice​

Because every query now has one fingerprint, the old fingerprints don't carry over. A cursor that a GET walk of Query Entities or Query Temporal Evolution of Entities handed out before the upgrade is refused, and the client has to start that walk again. Stored Entity Maps are removed, and a request that names one is answered as if the map had expired.

A single entity type in a hop, as in sensor{Device:humidity}==40, now limits the linked Entities to that type, where v1.0.0 read Device:humidity as a prefixed attribute name. No other broker I tried answers EXAMPLE 13's sensor{humidity}==40 the way the example says in both Query Entities and a Subscription, so there was no portable hop query to break.

A prefixed name or an absolute IRI in q, csf or orderBy can be written as it is, as in q=ex:speed>50, or in double quotes, as in q="ex:speed">50, and both select the same Entities. At the start of a hop's braces it has to be quoted, since an unquoted colon there ends the type list, and so does an IRI holding a dot. Andromeda gives names back without quotes wherever they read back the same, which is the form other brokers read. The upgrade quotes the names of the Subscriptions and Snapshot queries v1.0.0 stored, so each keeps the meaning v1.0.0 gave it.

Other brokers read a temporal q in four different ways. They test it against the instances in the window, as Andromeda does, against the current Entity, as annex C.5.5 does, against every instance whatever the window, or not at all. A client that needs one answer everywhere selects the Entities with Query Entities and asks the Temporal API for those identifiers.

Some answers change too. Wherever the two sides disagreed, one of them moved, sometimes the Subscription and sometimes Query Entities, and the changelog lists each one. A few fixes made things slower. near used to report two geometries as touching when a corner of one was the antipode of a point on the other. A pair of geometries that both have edges, and that the database finds within the distance, is now measured a second time, edge by edge. Measured in PostgreSQL alone, with 1,000 polygons of 500 vertices and a reference polygon of 2,000 vertices that overlaps 978 of them, that check takes 1.6 s where it used to take 0.7 s.

Other parts of the work made things faster. A periodic notification now goes through the same statements Query Entities runs, so it only reads the Entities its filters match. On a tenant with 100,000 Entities and a q on an attribute that 100 of them hold, each tick runs 2 statements instead of 401.

What the tests still miss​

The generated test compares which Entities each side matched, and for a Subscription, "no" means a notification never arrived. Notifications for one Subscription are sent side by side and can arrive out of commit order, so the test has no way to know the last one is in. It waits for as many notifications as Query Entities returned Entities, or until that wait times out, then three seconds more, and a wrong notification that arrives after that goes unnoticed.

The geo median sits exactly on its limit of 2 after both writes, and the q median sits on its limit of 3 after creation. After creation, 44% of the geo-queries that match anything match a single Entity. A change to either generator could trip one of those limits first.

The test only generates q filters and geo-queries. It doesn't generate scopeQ yet, and temporal queries, Entity Maps and federated reads have no Subscription to compare against, so each of them needs a comparison of its own.

Back to speed.value​

The bug from the start can't come back in the same form. What an attribute path addresses is decided once, when a filter is turned into its description. The architecture test stops anyone from matching on a term's syntax tree outside the module that does that. And a suite test asks Query Entities and a Subscription the same speed.value questions and expects the same empty answer from both.

The check is worth a few minutes on any broker. Subscribe with q=speed.value==80, create an Entity whose speed is 80, and send Query Entities the same q. Clause 4.9 says neither should select it. Agreement alone doesn't settle it, since some brokers select it on both sides.

A shared parser meant no comparison could say whether Device:humidity names a type or an attribute, and 228,069 empty answers said almost nothing about the evaluators that produced them. So most of the effort went into checking the text wherever both sides agreed, and into test cases that could tell one answer from another.