popoto.backends.postgres.validity¶
popoto.backends.postgres.validity
¶
Validity intervals and supersession on Postgres (#759 M3; plan §2 group D).
This module is the Postgres half of :class:~popoto.fields.validity_field.
ValidityField and :class:~popoto.fields.supersession.SupersessionProtocol:
the interval columns, supersede (SUPERSEDE_LUA phase for phase),
chain (WITH RECURSIVE), the open-claim pointers, the exclusion rule
every retrieval gate applies, and the field_call adapters the field layer
reads through. :class:PostgresValidityOps is mixed into
:class:~popoto.backends.postgres.PostgresBackend (through
:class:~.memory.PostgresMemoryOps).
Storage (plan §3, "Field → column type mapping"; a recorded departure)¶
The plan proposed <f> tstzrange. It cannot hold what the Redis indexes
hold, measured before this module was written (PostgreSQL 18.6):
- Precision.
timestamptzkeeps microseconds, so the epoch1700000000.1234567comes back1700000000.123457: a close instant one ulp after anas_ofreads as one at it, and the gate's bound is no longer bit-exact (invalid_at <= as_offlips). The Redis score is the fulldouble-- the M2a clock decision, for the same reason. - A close at the record's own start.
SUPERSEDE_LUAlets a record close at exactly itsvalid_from(the check isclose < start), andtstzrange(t, t)is the canonicalemptyrange, which keeps neither bound: the start the record had, and the close the chain recorded, are both lost. Alower > upperpair raises outright. - Partial intervals are not the reason, though they need care: a member
can sit in one index and not the other (an
import_stateshape), and the exclusion rule treats an absent end as "never excludes" and+infas "open" -- they differ atas_of = +inf. A range can say that (upper_inf('[t,)')is true,upper_inf('[t,infinity)')false), so this is no argument againsttstzrange; it is how the columns below spell it (NULLvs'Infinity').
So the interval is three double precision columns beside the field's own
column, which keeps the declared value as the Redis hash does:
<f>__valid_from-- thevalid_fromZSET score<f>__invalid_at-- theinvalid_atZSET score ('Infinity'= open)<f>__ingested_at-- theingested_atZSET score<f>__supersedes/<f>__superseded_by(text) -- thechain:rev/chain:fwdHASH entries for this record
NULL is "absent from that index". B-trees on the two gate columns serve
filter(validity__as_of=…); a supersede rewrites them only on close.
The open-claim pointers are a companion table <table>__<f>__open (digest
text PRIMARY KEY, member text REFERENCES <table>(_pk) ON DELETE CASCADE)
with an index on member, not the plan's partial UNIQUE on an identity
column: a record can be the open claim of several identities at once, and an
invalidate leaves the pointer naming the record it closed (the next
supersede on that identity reads it as "already closed"), neither of which a
per-row identity column can say. The cascade is on_delete's pointer
cleanup, matched on the exact key, so a never takes ab's pointer with
it (#750's drop_validity prefix over-match). The table is created on first
use, like popoto_recall_proposal.
Lock order (plan §2 supersede, §6 TD-2)¶
Every supersede on one (model, field) takes
pg_advisory_xact_lock(hashtext('popoto:validity:<schema>.<table>.<f>'))
first -- Redis's single thread, per model and field -- and then locks the
rows it reads FOR UPDATE in _pk order (COLLATE "C"). Two
supersedes therefore never interleave: two pointer writers, two explicit
writers, a pointer and an explicit writer, and the crossing chains that
deadlocked the POC (#750 B1: d1 -> X superseded by Y while d2 ->
Y is superseded by X) all run one after the other.
That is the head of the backend's one lock order (plan §6, TD-2; M2b's
:meth:~popoto.backends.postgres.PostgresBackend._record_locked): the
(model, field) lock, then the record-key advisory locks in _pk byte
order, then the row locks in _pk order. Every validity writer follows it:
supersede (record keys of the successor and the incumbent before its
FOR UPDATE), save_and_supersede / save_and_invalidate (all of the
supersede's locks before the save, through the lock adapter -- the save
would otherwise take the successor's key and row first and cross a concurrent
supersede naming it), import_state (a pointer writer), and
ObservationProtocol's batch (which locks a contradicted record's successor
with the batch). A plain save does not take the field lock; it takes its
record key and meets a supersede there, and its upsert re-reads the row it
waited on, so it cannot reopen a record the supersede closed (plan Race 2).
What remains is a caller's own transaction() that locks a record before a
supersede on it: Postgres detects that cycle and one side is aborted -- an
owned transaction retries; in the caller's transaction it is
:class:~popoto.backends.BackendRetryableError at once.
Never imports redis.
NOT_HANDLED = object()
module-attribute
¶
What :meth:PostgresValidityOps._validity_field_call returns for an op
it does not register.
PostgresValidityOps
¶
supersede, chain and the validity field_call adapters for
:class:~popoto.backends.postgres.PostgresBackend. Relies on the
backend's _table, _run and _atomically.
Source code in src/popoto/backends/postgres/validity.py
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 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 | |
supersede(spec, field, *, successor, incumbent, identity, mode, valid_from, invalid_at, now, uow=None, ingested_at=None, assert_valid_from=False, **options)
¶
SUPERSEDE_LUA, phase for phase, in one transaction.
mode is 'open' (open successor; close nothing),
'supersede' (close the incumbent -- incumbent, else the record
identity's pointer names -- chain it to successor and open
that) or 'invalidate' (as 'supersede'; without a successor
nothing is chained or opened). invalid_at is the close instant,
and every instant the caller leaves out is now.
Phases, after the (model, field) lock and the _pk-ordered row
locks: validation (reads and refusals only) -- a successor that
does not exist, an asserted incumbent that does not exist (a
pointer-resolved one that does not is "no incumbent"), a close
before the incumbent's own start, an asserted valid_from that
disagrees with the stored one -- raises the typed error the script's
reply maps to, with the same text, having written nothing; then
mutation -- close (only an open incumbent: closing is
idempotent), both chain links, the NX open of an open successor,
and the pointer repoint. Returns the closed record's key, or None.
A record that does not exist holds no interval here (the interval is
its row), so mode 'open' on an absent successor writes
nothing, where the script's ZADD NX would index a member with no
record (only a direct execute_supersede call can ask for that).
Source code in src/popoto/backends/postgres/validity.py
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 | |
chain(spec, field, id)
¶
The supersession chain through id, oldest first, in one
WITH RECURSIVE: back along supersedes, then forward along
superseded_by. [] when id has no valid_from (unsaved,
or never opened). A walk stops at a missing link, at a record it has
already visited (a cycle -- the forward walk counts the backward
walk's records as visited, as the Redis walk's shared seen set
does), and at a link naming a record with no valid_from (a hard
delete leaves the neighbour's link naming it).
Source code in src/popoto/backends/postgres/validity.py
validity_field_names(spec)
¶
The model's ValidityField names, in declaration-sorted order.
validity_columns(spec)
¶
The interval and chain-link columns for each ValidityField.
Source code in src/popoto/backends/postgres/validity.py
validity_indexes(spec, index_name)
¶
A B-tree on each gate column: filter(validity__as_of=…) and the
exclusion reads (invalid_at <= t, valid_from > t) are range
scans on them.
Source code in src/popoto/backends/postgres/validity.py
pointer_table(ts, field)
¶
<schema>.<table>__<f>__open: the open-claim pointers (digest ->
member) of one ValidityField.
Source code in src/popoto/backends/postgres/validity.py
ensure_validity_tables(conn, ts, spec)
¶
Create each ValidityField's pointer table if it is missing, on
conn and in its own transaction, under the DDL advisory lock: run at
the model's first use, right after its table is created or checked, so
no supersede ever has to create one inside a transaction that already
holds the model table's locks. CREATE … IF NOT EXISTS is idempotent,
so a process that finds the table does nothing.
Source code in src/popoto/backends/postgres/validity.py
excluded_sql(field, as_of, alias='t')
¶
invalid_at <= as_of OR valid_from > as_of: the rule every gate
applies (DECAY_SCORE_LUA's, the composite mask's,
resolve_excluded_keys'). An absent end (NULL) never excludes; an
open record (+inf) is closed only at as_of = +inf.
Source code in src/popoto/backends/postgres/validity.py
included_sql(field, as_of, alias='t')
¶
The gate as a WHERE term: TRUE when there is no gate (no
as-of, or a NaN one -- which excludes nothing in the Lua, where every
comparison with NaN is false), else NOT the exclusion rule.
Source code in src/popoto/backends/postgres/validity.py
range_bound(as_of)
¶
as_of as a range-read bound, refused as Redis refuses it: a NaN
bound makes ZRANGEBYSCORE/ZRANGESTORE reply min or max is not
a float, so the reads that are range reads on Redis (the filters, the
resolvers, the composite mask) raise QueryException with that text
here -- the same text, a different class (M1's divergence (v)). The decay
ranking's gate is a Lua comparison instead, and a NaN there excludes
nothing on both (:func:included_sql).
Source code in src/popoto/backends/postgres/validity.py
validity_cond_sql(field, value)
¶
filter(validity__as_of=t) / validity__current=…, compiled by
:mod:popoto.backends.planning to Cond(field, VALID_AT, (t, valid)).
valid=True: valid_from <= t AND invalid_at > t -- both ends
present, the two ZRANGEBYSCOREs ValidityField._members_valid_at
intersects. valid=False (__current=False): the members of either
index that are not valid at t, the Redis complement.
Source code in src/popoto/backends/postgres/validity.py
save_parts(ts, spec, obj, names)
¶
What ValidityField.on_save does on Redis, as parts of the save
upsert: SUPERSEDE_LUA in mode 'open'.
Returns (insert columns, ON CONFLICT overrides, DO UPDATE guards).
A new row opens at the declared valid_from (else the save clock),
ingested now, invalid_at = +inf. An existing row keeps its interval
(NX): an absent end is filled, and a closed record is never reopened
-- the guard is the row the upsert re-read after waiting on any
concurrent supersede (plan Race 2). A declared valid_from that
disagrees with the stored start fails the guard: nothing is written and
the caller raises ValidityValidFromConflictError, the script's
ARGV[8] check.
Source code in src/popoto/backends/postgres/validity.py
refuse_valid_from_conflict(backend, spec, obj, *, uow=None)
¶
Raise the VALID_FROM_CONFLICT error for a save whose upsert guard
refused it (:func:save_parts), with the numbers the script's reply
carries: the stored start, then the declared one, each as Lua's
tostring prints it.