popoto.backends.postgres.graph¶
popoto.backends.postgres.graph
¶
Co-occurrence edges and graph expansion on Postgres (#759 M4; plan §2 group F).
CoOccurrenceField keeps, on Redis, one sorted set per source key,
$CoOcF:<Model>:<field>:<src> -> {dst: weight}, written by
LINK_WITH_PRUNE_LUA / STRENGTHEN_CLAMP_LUA / WEAKEN_ALL_LUA and
walked by PROPAGATE_BFS_LUA. Here each field has one companion table::
<table>__<field>__edge (src text, dst text, weight double precision,
PRIMARY KEY (src, dst))
with one row per directed edge -- the members of src's sorted set. A
symmetric field writes both directions, as the Lua writes both sets, so the
two weights of a pair can differ exactly as they can on Redis (a prune or a
weaken_all touches one side only). There is no foreign key: Redis links
any two key strings, records or not. Every tie-break is COLLATE "C",
the sorted set's bytewise member order.
Writes (graph_update)¶
Each op is one statement, behind the record-key advisory locks of the edge
sets it writes (src, and dst when symmetric), sorted by _pk: the
backend's one lock order (plan §6). The lock is what makes a link's
count-then-prune atomic, as the Lua is. A record delete on a model with a
symmetric field also writes its partners' sets (the reverse edges), so it
takes the partners' record-key locks too, in the same sorted sequence
(:func:graph_delete_lock_sql).
link--LINK_WITH_PRUNE_LUAper direction: an existing edge keeps its weight and nothing is pruned; a new one is added, and when the set then holds more thanmax_edgesthe lowestcount - max_edgesby(weight, dst)are removed -- the new edge among them when it ranks lowest (it is then never inserted). The reply is the Lua number reply Redis sends, an integer: the weight truncated toward zero.strengthen--STRENGTHEN_CLAMP_LUA:min(old + delta, cap)with a missing edge as0, written without a prune (as on Redis); the reply istostring(new)(Lua's%.14g).unlink--ZREMper direction.weaken--WEAKEN_ALL_LUA: every edge ofsrctimesfactor, an edge below0.001afterwards removed; the reply is how many were.replace--import_state: the edge set replaced wholesale. A NaN weight is refused before any write (on Redis theDELETEhas already emptied the set whenZADDrefuses it -- a documented divergence).
The arithmetic is the Lua's, in double precision. Postgres raises where C
overflows or underflows, so the statements guard the one product that can
(weight * factor underflowing, whose edge is removed either way), and an
input outside the box where no step can leave the double range (a
non-finite or > 1e300 delta, a NaN weight or factor) takes
:meth:GraphMixin._graph_exact: the same steps in Python floats, which are
C doubles, inside one transaction.
Reads (graph_expand)¶
mode="bfs"--PROPAGATE_BFS_LUA. The Lua runs a FIFO queue with a visited map: an entry(pk, w, depth)expands, through the topmax_edgesneighbours ofpkby(weight, dst)descending, unless an earlier entry forpkhad a weight>= w; a neighbour is reached withw * decay * min(edge, cap)and kept when that is>= threshold; each result is the maximum weight it was reached with, seeds excluded. Withthreshold > 0every entry's weight is positive and the step is monotone inw, so an entry the visited map skips is dominated by the earlier one (heavier, and no deeper, so with at least as many hops left): the result is the maximum over every walk of at mostdepthhops whose weights stay>= threshold. Up toDefaults.PG_GRAPH_RECURSIVE_MAX_LAYERS(2) layers that is oneWITH RECURSIVEstatement, a layer per iteration, keeping each node's heaviest arrival per layer (:func:bfs_sql). The recursive statement sees only the previous layer, so it cannot apply the visited map and re-expands every reached node on every layer: past two layers its work grows with depth x fan-out where the Lua's stops (#781 review: 24.9 s against 0.10 s on a 400-node clique). Deeper calls run :meth:GraphMixin._graph_bfs_layeredinstead -- one statement per layer (:func:bfs_layer_sql) and the visited rule between layers, so they expand no more than the Lua does and stop after the last layer that improved a node, whateverdepthis. A statement timeout is never what bounds a graph read. Outside that box (threshold <= 0or below1e-290, a negative or non-finitedecay_per_hop, a non-finite cap) the step is not monotone and the visited map's order matters, so :func:simulate_bfsreplays the Lua's queue exactly in Python over the same top-max_edgesneighbour lists, fetched one layer per statement. Scores come back through%.14g, as the Lua'stostringsends them.mode="linked"--get_linked:ZREVRANGEBYSCORE +inf min LIMIT 0 n, one indexed read ofsrc's rows (graph_expandat depth 1 with the stored weights as scores, unclamped).mode="edges"--export_state'sZRANGE 0 -1 WITHSCORES.
Never imports redis.
GraphMixin
¶
graph_update / graph_expand for
:class:~popoto.backends.postgres.PostgresBackend.
Source code in src/popoto/backends/postgres/graph.py
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 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 | |
graph_update(spec, field, op, src, dst, amount, *, uow=None, cap=None, edges=None)
¶
One CoOccurrenceField write (module docstring). Returns what
the field method returns on Redis: link the integer reply as a
float, strengthen the %.14g new weight, weaken the number
of edges removed, unlink / replace None.
Source code in src/popoto/backends/postgres/graph.py
graph_expand(spec, field, seeds, *, depth, decay_per_hop, threshold, fanout, cap=None, mode='bfs')
¶
mode="bfs": propagate (scores through %.14g, seeds
excluded); "linked": get_linked for the one seed, threshold
being its min_weight and fanout its limit; "edges":
every edge of the one seed, ascending (export_state). Module
docstring for the semantics.
Source code in src/popoto/backends/postgres/graph.py
edge_table(ts, field)
¶
The qualified edge table of field on ts's model.
compile_graph(spec, schema, table)
¶
The edge companion table of each CoOccurrenceField: (name, DDL)
entries for :attr:TableSpec.companions. Pure.
Source code in src/popoto/backends/postgres/graph.py
graph_delete_sql(ts, spec)
¶
WITH CTEs that run CoOccurrenceField.on_delete inside a record
DELETE: each deleted key's own edges go, and for a symmetric field
the reverse edge in every set it linked to (the Redis hook removes the
key from exactly those sets). Returns the SQL prefix (empty when the model
has no graph field) and how many times the key array parameter appears in
it, in order.
Source code in src/popoto/backends/postgres/graph.py
graph_delete_lock_sql(ts, spec, keys)
¶
The record-key locks a record DELETE takes when the model has a
symmetric CoOccurrenceField: the deleted keys and every partner
whose edge set the reverse-edge CTE of :func:graph_delete_sql writes,
in one _pk-ordered sequence -- the backend's one lock order, so the
delete never row-locks a partner's edges without that partner's key
lock. Empty when there is no symmetric graph field (the deleted keys'
own locks then cover every row it writes).
The statement runs twice. The first takes the locks in order, with the
partners its snapshot saw; once it returns, the deleted keys are held,
and no new partner can appear (a link to a deleted key takes that
key's lock). The second sees, in a fresh snapshot, a partner linked
between the first's snapshot and its last lock -- normally none, and
re-taking a held advisory lock is a no-op -- so every edge set the
DELETE that follows writes is locked. Only such a racing partner is
locked out of order.
Source code in src/popoto/backends/postgres/graph.py
lua_integer_reply(value)
¶
float() of the integer Redis replies with for a Lua number: the
script's return weight is converted with a C (long long) cast,
truncating toward zero. Out of range the cast is the platform's; on
the arm64 and x86-64 servers measured, -inf and anything below
-2**63 reply -2**63. Above 2**63 (a weight over the cap,
reachable only with a cap past 2**63) arm64 saturates to
2**63 - 1 and x86-64 replies -2**63; this returns the arm64
value.
Source code in src/popoto/backends/postgres/graph.py
bfs_sql(table, *, fanout)
¶
The WITH RECURSIVE statement for PROPAGATE_BFS_LUA in its
monotone domain (module docstring). Parameters, in order: the seeds
(text[]), the decay per hop, the cap, the depth and the threshold.
One iteration is one BFS layer: each
frontier node's top fanout edges by (weight, dst) descending, the
Lua's product (w * decay) * min(edge, cap) -- the second *
saturating where Postgres would raise -- kept at >= threshold, and
each reached node's heaviest arrival in the layer carried on.
Source code in src/popoto/backends/postgres/graph.py
bfs_layer_sql(table, *, fanout)
¶
One BFS layer of :func:bfs_sql, from a frontier passed in: each
frontier node's top fanout edges by (weight, dst) descending, the
same product kept at >= threshold, and each reached node's heaviest
arrival. Parameters, in order: the decay per hop, the cap, the frontier's
keys (text[]) and weights (float8[]), the threshold. Weights
cross the wire as float8 text, which round-trips a double exactly.
Source code in src/popoto/backends/postgres/graph.py
simulate_bfs(neighbours, seeds, *, depth, decay, threshold, cap)
¶
PROPAGATE_BFS_LUA, statement for statement, in Python floats (C
doubles, as Lua's are). neighbours(nodes) returns each node's
ZREVRANGE 0 max_edges-1 WITHSCORES; it is called once per layer, for
every distinct node of the layer (a superset of the ones that expand).
Returns the raw weights, before tostring.