popoto.fields.validity_field¶
popoto.fields.validity_field
¶
Validity Field - Bitemporal Validity Intervals and Supersession Index State¶
This module provides :class:ValidityField, the validity axis for popoto
models (issue #580). Where DecayingSortedField answers "how important is
this memory right now?", ValidityField answers the prior question: "is this
memory still true at all?"
Motivation¶
An agent learns "user is on the free plan". Two weeks later it learns "user
upgraded to enterprise". Without a validity axis the stale fact keeps its place
in every index and only loses ground gradually, through decay — so it can still
be packed into the agent's context ahead of the correction. ValidityField
makes that first fact stop being a member of default retrieval the moment it
is superseded, while keeping it fully queryable in historical mode.
Design Philosophy¶
- Validity decides membership, decay decides ordering among the valid. The two axes compose and neither needs to know the other's constants.
- Not a :class:
~popoto.fields.sorted_field_mixin.SortedFieldMixin. This is load-bearing, not an oversight — see the class docstring. Validity must never win a query's ordering field. - Closed, never deleted. Superseding a record closes its interval; the
record and its chain links survive for provenance and
as_ofreplay. - No model-hash mutation for chain links (plan D3). Chain links live in two derived HASHes so an append-only journal (#560) can adopt this field unchanged.
- Valkey-safe. Core commands only (
ZADD/ZSCORE/ZREM/ZRANGEBYSCORE/HSET/HDEL/GET/SET/DEL/EXISTS) plus Lua 5.1. No Redis-module commands (BF./CMS./TS./TOPK.) anywhere.
Index Structure (plan D1) — six Redis keys per model/field::
$ValidityF:Model:field:valid_from ZSET member -> valid-from epoch
$ValidityF:Model:field:invalid_at ZSET member -> close epoch, +inf = open
$ValidityF:Model:field:ingested_at ZSET member -> ingest epoch
$ValidityF:Model:field:chain:fwd HASH old redis_key -> superseding key
$ValidityF:Model:field:chain:rev HASH new redis_key -> superseded key
$ValidityF:Model:field:open:{digest} STRING identity digest -> open record
(The $ValidityF prefix is auto-derived by the FieldBase metaclass from
the class name ValidityField.)
An as-of-t membership test is valid_from <= t AND invalid_at > t: two
ZRANGEBYSCOREs intersected, or two ZSCOREs inside Lua. +inf as the
open-interval sentinel is native to both Redis and Valkey sorted sets.
Example
from popoto import Model, KeyField, ValidityField
class Fact(Model): fact_id = KeyField() validity = ValidityField()
old = Fact(fact_id="plan-1").save() # interval opens at now, closes at +inf new = Fact(fact_id="plan-2").save()
The explicit close below is NOT optional (issue #693). Saving alone only¶
ever OPENS intervals, so a save-only model's exclusion set stays empty,¶
unless a save declares a future valid_from.¶
Close old and chain it to new in one atomic EVAL:¶
ValidityField.execute_supersede( Fact, "validity", new_member=new.db_key.redis_key, mode="supersede", old_member=old.db_key.redis_key, )
Fact.query.filter(validity__current=True) # -> only new
Fact.query.filter(validity__as_of=earlier) # -> old
ValidityError
¶
Bases: ValueError
Base for every typed failure raised out of :data:SUPERSEDE_LUA.
Subclasses :class:ValueError deliberately (plan D4). Two shipped contracts
depend on it: ObservationProtocol._apply_supersession degrades on
except (TypeError, ValueError), and the V0 test suite asserts
pytest.raises(ValueError) for close-before-start. Widening those to a new
base class would be a silent behavior change on a signal path.
Source code in src/popoto/fields/validity_field.py
ValidityMemberAbsentError
¶
Bases: ValidityError
A member the caller named does not exist at the instant of the write.
Raised for a successor that was never saved (including the "Model:None"
key an unsaved instance yields) and for an incumbent named explicitly via
old_member. An incumbent merely resolved from the open-claim pointer is
a hint, not an assertion, and its absence means "no incumbent" instead.
Source code in src/popoto/fields/validity_field.py
ValidityCloseBeforeStartError
¶
Bases: ValidityError
A close instant precedes the record's own stored valid_from.
ValidityValidFromConflictError
¶
Bases: ValidityError
An asserted valid_from disagrees with the already-stored start.
Valid-time has exactly one writer: the field value at construction. Any other
writer that asserts a disagreeing start gets this rather than losing
silently to ZADD NX.
Source code in src/popoto/fields/validity_field.py
ValidityField
¶
Bases: Field
Bitemporal validity interval for each record of a model.
Declared as a plain field::
class Fact(Model):
fact_id = KeyField()
validity = ValidityField()
The stored field value is the record's valid-from epoch (a float); the
interval state itself lives in the six derived Redis keys documented in the
module docstring, maintained by :data:SUPERSEDE_LUA.
Declaring the field is NOT enough to exclude anything (issue #693)¶
A plain .save() routes through :meth:on_save in mode 'open': it
writes valid_from = save time (or a caller-declared epoch, see below)
and invalid_at = +inf, and nothing else. +inf never satisfies the
invalid_at <= as_of test in :meth:resolve_excluded_keys, so with
respect to that branch, a save that does not declare a future
valid_from gets a fully populated pair of interval ZSETs and an
exclusion set that stays permanently empty. That is only half of
resolve_excluded_keys, though: its other, independent branch excludes
on valid_from > as_of, and :meth:on_save uses field_value as the
valid-from epoch whenever it is numeric. So a plain .save() that
declares a future valid_from is excluded, until that moment arrives
— the one thing a save without a producer can exclude. A save also never
registers a record as the incumbent for any identity — the
{prefix}:open:{digest} pointer is written by :data:SUPERSEDE_LUA
itself, so a later
SupersessionProtocol.supersede(successor, identity_key=...) finds no
incumbent, closes nothing, and returns None.
Closing an interval requires an explicit producer. Today there are four:
- :meth:
SupersessionProtocol.supersede/ :meth:~popoto.fields.supersession.SupersessionProtocol.save_and_supersede— use one of these for every identity-bearing write, including the first claim about an identity, or the second claim will close nothing. - :meth:
~popoto.fields.supersession.SupersessionProtocol.invalidate/ :meth:~popoto.fields.supersession.SupersessionProtocol.save_and_invalidate— the identity-free counterpart of the pair above. ProvenanceJournal.ObservationProtocol.on_context_usedwith the"contradicted"outcome andinstance._superseded_byset — see_apply_supersession. This is still an explicit application call, not an inference.
The empty-set-versus-None distinction is real but invisible to an
adopter: gating did run, and excluded nothing. Whether this should stay
imperative is the open question on issue #693.
Why this is NOT a SortedFieldMixin (plan D2)¶
This is load-bearing and must not be "improved". ModelOptions.add_field
classifies any SortedFieldMixin into _meta.sorted_field_names, which
puts the field in filter_for_keys_set's first loop — where a returned
list becomes Query._sorted_field_order and the field can win the
query's ordering. Validity is membership, not priority: it must never order
results. As a plain Field it lands in the second loop and returns a
set (hence :meth:filter_query's set return type — a list there
would silently reintroduce the ordering bug). It also stays out of the
reindex/migration loops that iterate sorted_field_names.
Query params (see :meth:get_filter_query_params):
- {field}__current=True — records valid right now
- {field}__current=False — the complement (closed / not-yet-started)
- {field}__as_of=t — records valid at epoch t
These are deliberate queries: they consume a filter param and therefore disable sorted-range limit pushdown. That is exactly why the default retrieval path gates on validity server-side instead of via a filter kwarg.
Source code in src/popoto/fields/validity_field.py
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 | |
find_open_pointers_for_member(model, field_name, member_key)
classmethod
¶
Return the pointer keys under {prefix}:open:* that name member_key.
There is no record -> identity-digest reverse lookup by design (plan D1
fixes the key count at six, and the digest is opaque: identity is
caller-defined and hashed by SupersessionProtocol.identity_key), so
the only way to answer "which identities currently claim this record as
their open one?" is to SCAN the pointer keyspace and compare values.
Both callers are admin/rare paths — :meth:on_delete and
:meth:export_state — never save or read.
A record may legitimately match zero pointers: it was never superseded on an identity, or it has already been closed and the pointer moved on.
Source code in src/popoto/fields/validity_field.py
export_state(model_instance, field_name, field_value, **kwargs)
classmethod
¶
Export this record's interval scores, chain links, and open claims.
Reads the member's score from each of the three interval ZSETs, its
own forward/reverse chain-link entries, and every identity-scoped
open-claim pointer ({prefix}:open:{digest}, see
:meth:get_open_pointer_key) that currently names this record.
All six derived keys are therefore carried. The pointer matters more
than its "per-identity, not per-record" shape suggests:
SupersessionProtocol.supersede(new, identity_key=...) resolves the
incumbent solely through it (old_member='', and
:data:SUPERSEDE_LUA GETs KEYS[4]). A round trip that dropped
the pointer would leave the next supersession on that identity closing
nothing and writing no chain link, while still repointing the pointer
at the newcomer -- orphaning the incumbent open forever. Gating is
subtractive (see :meth:resolve_valid_keys), so that orphan stays
fully retrievable: the same silent resurrection roundtrip_policy =
"carry" exists to prevent, deferred by one supersession.
Capturing the pointers costs a SCAN of {prefix}:open:* per
record (see :meth:find_open_pointers_for_member) because the digest
is opaque and there is no record -> digest reverse lookup. Export is
an admin-path operation and that cost is accepted deliberately, on
the same reasoning as :meth:on_delete's scan.
Returns:
| Type | Description |
|---|---|
Optional[dict[str, Any]]
|
``{"valid_from": float, "invalid_at": float | "+inf", |
Optional[dict[str, Any]]
|
"ingested_at": float, "chain_fwd": str | None, |
Optional[dict[str, Any]]
|
"chain_rev": str | None, "open_pointers": list[str]}``, or |
Optional[dict[str, Any]]
|
|
Optional[dict[str, Any]]
|
saved through this field, or already deleted). |
Optional[dict[str, Any]]
|
holds identity digests, not full Redis keys, so the destination |
Optional[dict[str, Any]]
|
rebuilds them under its own prefix; it is commonly empty -- a |
Optional[dict[str, Any]]
|
record that was never superseded on an identity, or one already |
Optional[dict[str, Any]]
|
closed, legitimately owns no pointer, and its interval and chain |
Optional[dict[str, Any]]
|
state are still exported. |
Source code in src/popoto/fields/validity_field.py
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 | |
import_state(model_instance, field_name, state, **kwargs)
classmethod
¶
Restore this record's interval scores and chain links after import.
Written with plain ZADD/HSET -- deliberately NOT through
:data:SUPERSEDE_LUA and NOT with the NX guards on_save
uses. The transfer driver calls import_state after save(),
so on_save has already run: it seeds valid_from /
ingested_at / invalid_at via ZADD NX in mode="open",
i.e. a fresh, open interval with no close time and no chain. An
NX write here would be a silent no-op against those
already-present scores, discarding the carried close time and chain
-- exactly the resurrection bug this field exists to prevent.
Plain ZADD/HSET overwrite instead.
Carried open-claim pointers are restored with a plain SET, for
the same reason: on_save cannot write them at all on this path
(it calls :meth:execute_supersede with no identity_digest, so
KEYS[4] is '' and :data:SUPERSEDE_LUA skips the SET),
and an unconditional SET is what makes the identity's next
supersession resolve this record as the incumbent (see
:meth:export_state for why dropping it resurrects records). Only
the digests actually captured at export are written, so a record
that owned no open claim still writes none.
Chain links are restored independently of import order: HSET
does not require the counterpart record to already exist, and
_walk_links-style chain traversal already treats a link to a
record with no interval entry as a chain end (see
:meth:on_delete's "Known limitation" note), so a partially
imported chain converges once both sides have landed.
Source code in src/popoto/fields/validity_field.py
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 | |
get_prefix_db_key(model, field_name)
classmethod
¶
Return the $ValidityF:{Model}:{field} prefix all six keys extend.
Source code in src/popoto/fields/validity_field.py
get_valid_from_key(model, field_name)
classmethod
¶
Redis key of the valid_from ZSET (member -> valid-from epoch).
Source code in src/popoto/fields/validity_field.py
get_invalid_at_key(model, field_name)
classmethod
¶
Redis key of the invalid_at ZSET (member -> close epoch, +inf = open).
Source code in src/popoto/fields/validity_field.py
get_ingested_at_key(model, field_name)
classmethod
¶
Redis key of the ingested_at ZSET (member -> transaction-time epoch).
Source code in src/popoto/fields/validity_field.py
get_chain_fwd_key(model, field_name)
classmethod
¶
Redis key of the forward chain HASH (old redis_key -> superseding key).
Source code in src/popoto/fields/validity_field.py
get_chain_rev_key(model, field_name)
classmethod
¶
Redis key of the reverse chain HASH (new redis_key -> superseded key).
Source code in src/popoto/fields/validity_field.py
get_open_pointer_key(model, field_name, identity_digest)
classmethod
¶
Redis key of the open-claim pointer STRING for one identity digest.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ModelLike
|
The model class (or instance) owning the field. |
required |
field_name
|
str
|
Name of the |
required |
identity_digest
|
str
|
Opaque, already-normalized identity token — see
|
required |
Source code in src/popoto/fields/validity_field.py
get_interval_keys(model, field_name)
classmethod
¶
Return (valid_from_key, invalid_at_key) for a model/field pair.
This is the stable seam every other validity consumer builds on: the
decay-Lua gate passes these two as extra KEYS, the composite-score
mask ZRANGESTOREs from them, and the assembler's
_resolve_excluded_keys reads them directly. Returned in the order
(valid_from, invalid_at); an as-of-t member satisfies
valid_from <= t AND invalid_at > t.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ModelLike
|
The model class (or instance) owning the field. |
required |
field_name
|
str
|
Name of the |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, str]
|
A 2-tuple of Redis key strings. |
Source code in src/popoto/fields/validity_field.py
get_all_keys(model, field_name)
classmethod
¶
Return the five non-identity keys as a name -> Redis key mapping.
Keys: valid_from, invalid_at, ingested_at, chain_fwd,
chain_rev. The sixth key (the per-identity open pointer) is excluded
because it is parameterized by identity digest — use
:meth:get_open_pointer_key for that one.
Source code in src/popoto/fields/validity_field.py
resolve_valid_keys(model, field_name, as_of=None)
classmethod
¶
Return the record keys whose interval covers as_of.
Two read-only ZRANGEBYSCOREs intersected:
valid_from <= as_of AND invalid_at > as_of.
.. warning::
This is a whitelist: a record with no entry in either ZSET is
absent from the result. That makes it wrong for retrieval gating,
and it is deliberately not used by any retrieval path. All three
gating layers are subtractive — they exclude records that are
positively known to be closed or not-yet-started, and leave
unmanaged records (no interval at all) fully visible. Using this
method to gate retrieval would silently hide every record that
predates the field's adoption on a model. The assembler uses
ContextAssembler._resolve_excluded_keys instead, and the query
layer uses QueryBuilder._apply_validity_mask.
Retained as the public, deliberate-query helper for callers that
genuinely want "which records positively claim validity at t" —
e.g. audit and provenance tooling, not context assembly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ModelLike
|
The model class (or instance) owning the field. |
required |
field_name
|
str
|
Name of the |
required |
as_of
|
Optional[float]
|
Epoch seconds to evaluate at. |
None
|
Returns:
| Type | Description |
|---|---|
set[str]
|
|
set[str]
|
every consumer compares against |
set[str]
|
a |
set[str]
|
where the query layer intersects raw index replies. |
Note
This is a point-in-time snapshot of a live store. A supersession landing after the read is not reflected until the next call — the same accepted property tag scoping already has (plan Race 3).
Source code in src/popoto/fields/validity_field.py
resolve_excluded_keys(model, field_name, as_of=None)
classmethod
¶
Return the record keys to DROP as of as_of (#648).
The subtractive counterpart to :meth:resolve_valid_keys, and the one
every retrieval path actually wants. Two read-only ZRANGEBYSCOREs,
unioned: invalid_at <= as_of (already closed) and
valid_from > as_of (not yet started) — the exact mirror of the two
ranges :meth:resolve_valid_keys intersects.
.. warning::
This returns an exclusion set, not a whitelist, and that is
deliberate. A record with no entry in either interval ZSET is
unmanaged and stays fully retrievable. Resolving the valid set
instead — via :meth:resolve_valid_keys, whose own warning is the
other half of this one — would silently hide every record that
predates the day a ValidityField was added to an existing model,
since none of those has an interval until it is next saved. That is a
data-visibility regression, not a stricter gate. Do not "simplify"
this into a valid-key intersection.
This method lives beside resolve_valid_keys precisely so the
warning and the trap it warns about are read together. It used to
live in ContextAssembler._resolve_excluded_keys, a different file
from the method it forbids.
The exclusive lower bound on valid_from is spelled f"({t}",
while the invalid_at upper bound is inclusive. Redis renders the
+inf open sentinel such that an open record never matches
<= as_of. Both bound conventions are this method's business, not a
caller's.
Callers own the policy questions this does not answer: whether the
model declares a ValidityField at all, and whether the
Defaults.VALIDITY_GATING_ENABLED kill switch is on (which must be
read at call time, never captured at import, so a deploy-level switch
takes effect for adopters who cannot edit model code).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ModelLike
|
The model class (or instance) owning the field. |
required |
field_name
|
str
|
Name of the |
required |
as_of
|
Optional[float]
|
Epoch seconds to evaluate membership at. |
None
|
Returns:
| Type | Description |
|---|---|
set[str]
|
|
set[str]
|
gating ran and excluded nothing — which is not the same as a |
set[str]
|
caller's |
Note
A point-in-time snapshot of a live store. A supersession landing after the read is not reflected until the next call.
Source code in src/popoto/fields/validity_field.py
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 | |
is_valid_at(model, field_name, member_key, as_of=None)
classmethod
¶
Return whether one record's interval covers as_of.
Two ZSCOREs rather than two range reads — the single-member form of
:meth:resolve_valid_keys. A member absent from either ZSET is not valid
(it has no interval).
Source code in src/popoto/fields/validity_field.py
execute_supersede(model, field_name, *, new_member='', mode='open', now=None, valid_from=None, ingested_at=None, close_at=None, old_member='', identity_digest='', assert_valid_from=False, pipeline=None)
classmethod
¶
Run :data:SUPERSEDE_LUA once against this model/field's six keys.
The single seam through which every validity mutation flows —
ValidityField.on_save and SupersessionProtocol both call it, so
there is exactly one place that knows the script's KEYS/ARGV order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ModelLike
|
The model class (or instance) owning the field. |
required |
field_name
|
str
|
Name of the |
required |
new_member
|
str
|
Redis key of the record whose interval opens. Empty for
a pure |
''
|
mode
|
str
|
|
'open'
|
now
|
Optional[float]
|
Epoch seconds to use as the script's clock. Defaults to
|
None
|
valid_from
|
Optional[float]
|
Valid-from epoch for |
None
|
ingested_at
|
Optional[float]
|
Transaction-time epoch for |
None
|
close_at
|
Optional[float]
|
Explicit close epoch for the incumbent. Defaults to |
None
|
old_member
|
str
|
Explicit incumbent key, bypassing identity resolution. |
''
|
identity_digest
|
str
|
Identity digest naming the open-claim pointer. When
empty, |
''
|
assert_valid_from
|
bool
|
When |
False
|
pipeline
|
Optional[Pipeline]
|
Optional external pipeline. When given, the EVAL is queued
(following |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
The closed member key as |
Any
|
or the |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
ValidityMemberAbsentError
|
If |
ValidityCloseBeforeStartError
|
If |
ValidityValidFromConflictError
|
If |
Note
The ResponseError -> typed-exception remap lives on the
non-pipeline branch only. On a caller-supplied pipeline redis-py
raises during pipe.execute() result parsing, long after this
method returned, so the caller sees a raw
redis.exceptions.ResponseError. Use
:meth:SupersessionProtocol.save_and_supersede, which owns its
execute(), to get a typed error in pipeline shape.
Source code in src/popoto/fields/validity_field.py
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 | |
warn_if_ttl(model, field_name)
classmethod
¶
Warn once when a ValidityField model also declares a TTL.
A TTL truncates supersession chains and silently breaks as_of
correctness: the expired record vanishes while its chain links and
interval entries remain. This warns rather than raises — refusing would
break adopters who legitimately want bounded history (plan D9).
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in src/popoto/fields/validity_field.py
on_save(model_instance, field_name, field_value, pipeline=None, **kwargs)
classmethod
¶
Open (or re-affirm) this record's validity interval.
Routes through :data:SUPERSEDE_LUA in mode 'open' rather than
issuing a bare ZADD, which is what makes the save path safe against
plan Race 2: the script's ZSCORE/NX guards mean a save that
interleaves with a concurrent supersession can never resurrect an
already-closed record, and a re-save never shifts an existing interval's
start or ingest time.
field_value is used as the valid-from epoch when it is numeric;
otherwise save time is used. The write is idempotent, so repeated saves
of an open record are no-ops on the index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_instance
|
Model
|
The instance being saved. |
required |
field_name
|
str
|
Name of this field on the model. |
required |
field_value
|
Any
|
The declared valid-from epoch, or |
required |
pipeline
|
Optional[Pipeline]
|
Optional external pipeline; the EVAL is queued onto it. |
None
|
**kwargs
|
Any
|
Accepted for forward compatibility. |
{}
|
Returns:
| Type | Description |
|---|---|
Any
|
The |
Source code in src/popoto/fields/validity_field.py
pre_save_validate(model_instance, field_name, field_value, **kwargs)
classmethod
¶
Refuse a save that declares a valid_from the index disagrees with.
Runs from the single pre-split dispatch site in Model.save(), before
any write is issued or queued — which is the point. Raising from
:meth:on_save would be too late on a model that also declares
IndexedFieldMixin fields: those commit their hash values and index
entries eagerly, against live Redis, before ValidityField.on_save
ever runs (plan D5 half 1, the same treatment #476 gave the
unique-conflict window).
A cheap client-side pre-check for a good error message; the authoritative
comparison is in :data:SUPERSEDE_LUA under ARGV[8], evaluated
atomically (plan Race 4). A racing pre-check can only produce a false
negative, which the script then catches.
Source code in src/popoto/fields/validity_field.py
get_valid_from(model, field_name, member_key=None)
classmethod
¶
Return the record's effective valid-from — the index score.
instance.validity is the declared value: None there means
"not declared, defaulted to the save clock". This returns what the
valid_from index actually holds, which is what every as_of query
answers against (plan D5 half 2). The two differ legitimately, and
reading this is how an operator reconciles a record whose hash and index
already disagree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ModelLike
|
The model class, or a live instance. |
required |
field_name
|
str
|
Name of the |
required |
member_key
|
Optional[str]
|
The record's Redis key. Defaults to |
None
|
Returns:
| Type | Description |
|---|---|
Optional[float]
|
The stored valid-from epoch, or |
Optional[float]
|
entry in the index. |
Source code in src/popoto/fields/validity_field.py
on_delete(model_instance, field_name, field_value, pipeline=None, **kwargs)
classmethod
¶
Remove every trace of this record from the validity keyspace.
ZREM from the three interval ZSETs, HDEL from both chain HASHes,
and clear any open-claim pointer still aimed at the record. Records are
normally closed, not deleted — this hook exists so an explicit
delete() (or a key migration, which calls it with saved_redis_key)
does not leave orphaned index members behind.
Pointer cleanup scans {prefix}:open:* because the pointer keyspace is
keyed by identity digest, not by member — the reverse lookup does not
exist by design (plan D1 fixes the key count at six). This is a
delete-time-only cost on a path that is rare relative to save and read;
adding a seventh per-record back-pointer key to avoid it was rejected as
the worse trade.
Known limitation: the deleted key is removed from both chain HASHes as a
field, but a neighbor's link may still name it as a value (fwd
holds old -> deleted). Scrubbing the value side would mean an
HGETALL of the whole chain on every delete. Chain traversal treats a
link to a record with no interval as a chain end, which is the correct
reading of a hard-deleted link.
Returns:
| Type | Description |
|---|---|
Any
|
The |
Source code in src/popoto/fields/validity_field.py
get_filter_query_params(field_name)
¶
Declare the two deliberate validity lookups.
{field}__as_of=t (records valid at epoch t) and
{field}__current=True|False (valid now / the complement).
Unioned with super()'s set per the base-class contract.
Source code in src/popoto/fields/validity_field.py
filter_query(model, field_name, **query_params)
classmethod
¶
Resolve validity lookups to a set of matching Redis keys.
Two ZRANGEBYSCORE reads intersected — valid_from <= t AND
invalid_at > t. __current=True evaluates at now;
__current=False returns the complement (every member with an
interval that does not cover now: closed, or not yet started). Multiple
params AND-intersect, consistent with the rest of filter_for_keys_set.
Returns a set and never a list: the query layer turns a list
return into Query._sorted_field_order, and validity must never order
results (plan D2).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Model
|
The model class being queried. |
required |
field_name
|
str
|
Name of this field on the model. |
required |
**query_params
|
Any
|
|
{}
|
Returns:
| Type | Description |
|---|---|
set[Any]
|
|
set[Any]
|
reply type) for records matching every supplied param. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/popoto/fields/validity_field.py
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 | |
map_lua_error(e)
¶
Return the typed exception for a :data:SUPERSEDE_LUA error reply.
Package-internal, deliberately without a leading underscore: three call
sites across two packages import it (supersession,
recipes.provenance_journal), which is more reach than a private name
honestly describes. It stays out of popoto.__all__ -- internal to the
package, not to the module.
Returns the mapped exception instance, or e itself when no token
matches. It never raises: every call site is spelled
raise map_lua_error(e) from e, so a helper that raised internally would
leave that expression unfinished, and one that returned None would turn
the call site into a TypeError.
The reply is a space-separated string whose first token is a stable
POPOTO_VALIDITY_* constant; the remaining tokens are diagnostic detail
for humans and are never parsed.