Original query:

SELECT
*
FROM
"Foo"     AS  Foo_1
JOIN
    engine.idents
ON
    engine.idents.STATE_NAME    =   Foo_1.STATE_NAME
WHERE
    engine.idents.IDENTITY  =   'KA-1731164427398417'
AND Foo_1.CONTRACT_NAME         =   'storage-microbench'
AND Foo_1.TX_INDEX              =   (
        SELECT
            MAX(Foo_2.TX_INDEX) AS  MAX_1
        FROM
        "Foo"     AS  Foo_2
        WHERE
            Foo_1.KEY                                   =   Foo_2.KEY
        AND Foo_1.CONTRACT_NAME                         =   Foo_2.CONTRACT_NAME
        AND Foo_1.STATE_NAME                            =   Foo_2.STATE_NAME
        AND (Foo_2.TX_INDEX, Foo_2.MINOR_TX_INDEX)  <=  (671003, 0)
    )
AND (
        Foo_1.MINOR_TX_INDEX    =   (
            SELECT
                MAX(Foo_2.MINOR_TX_INDEX)   AS  MAX_2
            FROM
            "Foo"     AS  Foo_2
            WHERE
                Foo_1.KEY               =   Foo_2.KEY
            AND Foo_1.CONTRACT_NAME     =   Foo_2.CONTRACT_NAME
            AND Foo_1.STATE_NAME        =   Foo_2.STATE_NAME
            AND Foo_2.TX_INDEX          =   671003
            AND Foo_2.MINOR_TX_INDEX    <=  0
        )
    OR  Foo_1.MINOR_TX_INDEX    =   (
            SELECT
                MAX(Foo_2.MINOR_TX_INDEX)   AS  MAX_3
            FROM
            "Foo"     AS  Foo_2
            WHERE
                Foo_1.KEY           =   Foo_2.KEY
            AND Foo_1.CONTRACT_NAME =   Foo_2.CONTRACT_NAME
            AND Foo_1.STATE_NAME    =   Foo_2.STATE_NAME
            AND Foo_2.TX_INDEX      <   671003
            AND Foo_2.TX_INDEX      =   Foo_1.TX_INDEX
        )
    )

AND VALUE @> '{"some_text": "foo-19361"}'
ORDER BY
    Foo_1.STATE_NAME        ASC
,   Foo_1.TX_INDEX          ASC
,   Foo_1.MINOR_TX_INDEX    ASC
,   Foo_1.KEY               ASC