Sync
****

Synchronization primitives for coordinating participants.

This module contains the core building blocks for synchronous
experiments. If you have not seen PsyNet's synchronization features
before, the key idea is simple: participants move through a timeline,
sometimes waiting for other participants to arrive at the same point.
We implement that waiting logic with barriers, and we implement
grouping logic with groupers and sync groups.


Glossary
========

Barrier
   A timeline element that pauses participants until some release
   condition is satisfied (for example, "wait until two participants
   arrive"). Barriers are subclasses of "Barrier"/"GroupBarrier". By
   default the browser preserves the current page and shows a
   lightweight hold indicator while it waits.

Grouper and sync group
   A "SimpleGrouper" (or other grouper) is a timeline element that
   forms "SyncGroup" rows once enough participants are available.
   Group barriers rely on these groups to decide who to release
   together. A "Regrouper" forms new groups every round, optionally
   within an existing group. Each group records the grouper that
   formed it and its "within" group, and each member's link records
   their role, so round counts, roles and when each pool was last
   split are read from these rows.

Barrier definition and instance
   A "BarrierDefinition" identifies the public waiting area. A
   "BarrierInstance" stores the stable behavior for one group visit.
   "ParticipantLinkBarrier" rows attach participants to that visit. At
   most one active instance exists per group visit, and ungrouped
   barriers share one active pool per barrier ID. Keeping definition,
   visit, and work-claim identities separate lets multiple worker
   processes cooperate without using mutable metadata as a mutex.

Whom a group barrier waits for
   A "GroupBarrier" waits for every active member of its group,
   wherever they are in the timeline; nothing about their position is
   inferred. A member stops being waited for only by leaving the group
   ("leave_group", "late_action", "max_wait_action", failing or
   finishing). The release's round, if any, is the "SyncGroupRound"
   that every released member's unfinished trial is in
   ("_common_round"). If every member is waiting, but no barrier of
   the group has them all, nothing can pass: each "check_barriers"
   sweep looks for such groups ("_report_divergences") and records
   each as an error once, with a token naming the group and the
   barriers, so later sweeps skip it until the group diverges at other
   barriers.


Where this shows up in a timeline
=================================

The most common pattern is:

1. A grouper runs early in the timeline to create sync groups.

2. A "GroupBarrier" appears later in the timeline to pause
   participants until the group is ready.

3. After release, the timeline continues with shared or individual
   tasks.


How processing works
====================

When a participant reaches a barrier, "Barrier.receive_participant":

* Registers the definition and resolves a stable instance in the
  request's transaction. Group barriers use one instance per sync-
  group visit; groupers retain a shared waiting-pool instance.

* Inserts a "ParticipantLinkBarrier" row marking the participant as
  waiting.

A scheduled task in "Experiment._check_barriers" calls
"check_barriers" in this module. That loop:

* Dissolves sync groups whose dissolution waited because a member was
  busy in their own request (see "SyncGroup._dissolve").

* Applies "max_wait_time" to waiters whose hold or waiting-page
  deadline has passed. Their own request normally does this, so
  waiters who left would otherwise stay.

* Finds waiting barrier instances and checks them least recently
  checked first, new or changed ones with a head start, within a per-
  sweep time budget.

* Claims each with a PostgreSQL advisory transaction lock on a
  dedicated connection, leaving definition and instance metadata
  available to arrival requests. That extra transaction stays open
  until this poller's skip-after-commit finishes.

* Locks waiters, and their groups that accept top-ups, with "NOWAIT".
  If a waiter or top-up group is already locked (for example by "POST
  /response" or a newcomer joining), it skips that barrier this tick
  instead of blocking the poller.

* Evaluates the barrier's release hooks in an isolated transaction,
  then skips waiters **this poller** released, one row at a time,
  after that commit.

* Logs and skips failures per barrier so one bad barrier does not
  stall others.

* Keeps hold-wake publishes unpublished until the sweep returns.

* Reports groups whose members wait at different barriers of the
  group.

Each default barrier visit links to a durable "TimelineHoldRecord".
Releasing the link accounts waiting through the release time and
queues a targeted browser wake. After the database transaction
commits, PsyNet sends that wake with "publish_to_participants" to the
participant's checked connections; the browser then rechecks the
authoritative link state. See "Timeline holds" in Page rendering and
lifecycle.

"Barrier" also queues those hooks when a participant arrives. After
the arrival transaction commits, the response route evaluates the
barrier in a short coordination transaction before rendering. That
lets a "Grouper" form groups and a "GroupBarrier" release the group
without waiting for the poller. Arrivals submitted with Next at a
"Regrouper" with "every" are usually the exception: they cannot make
the pool ready, so they queue no check and the poller normally enacts
each due tick. An arrival or reload in "GET /timeline" still checks
the waiter's visit (see PsyNet issue #1159). Ungrouped arrivals at a
"within" regrouper, and subclasses that override
"choose_who_to_release" or "check_waiting_participants", keep the
arrival check; see "Regrouper._queue_check_on_arrival()". Last-arrival
does not skip partner timeline cursors after that commit; partners
leave on overlay wake (or this poller, if it won the release). Waiter
and top-up group rows stay "NOWAIT" during the check so a locked
partner or group cannot stall that request for "lock_timeout".

Callable attributes on barriers (e.g., "on_release") persist through
"psynet.barrier_spec" so each "BarrierInstance" keeps stable release
behavior without pickling waiting pages. The reconstructed object is a
release/callback receiver, not a wait page. See "Barrier" for which
methods are live-only.

class psynet.sync.Barrier(id_, waiting_logic=None, waiting_logic_expected_repetitions=None, max_wait_time=20, fix_time_credit=False, expected_wait=None, waiting_message=None, release_grace=<class 'psynet.utils.NoArgumentProvided'>, waiting_screen=None)

   Bases: "EltCollection"

   A barrier is a timeline construct that holds participants in a
   waiting area until certain conditions are satisfied to release
   them. The decision about which participants to release at any given
   point is taken by the "choose_who_to_release" method, which the
   user is expected to provide.

   Timeline construction and wait UI run on this live object. Barrier
   checks, "on_release", and arrival-notice lookups reconstruct a
   separate object from "barrier_from_spec_json()". That reconstructed
   object has "id", custom release state, scalar presentation
   ("waiting_message", timeouts), and notification settings. It does
   not include wait-page construction ("waiting_logic",
   "waiting_screen", "_uses_timeline_hold" and the expected
   repetitions of "waiting_logic").

   Call "check_waiting_participants()", "choose_who_to_release()", and
   "release()" on reconstructed objects. Keep "receive_participant()"
   on the live timeline barrier; arrival overlay notify
   ("_notify_arrivals") is live-only as well.

   Parameters:
      * **id** -- ID parameter for the barrier. Barriers with the same
        ID share waiting areas; this allows participants at different
        points in the timeline to share the same waiting areas.

      * **waiting_logic** -- Either a single timeline element or a
        list of timeline elements (created by "join") that is to be
        displayed to the participant while they are waiting at the
        barrier. Use it to give participants something to do while
        they wait, such as filler trials, and "waiting_screen" to show
        them something. If left at the default value of "None", the
        participant sees "waiting_screen", or their current page
        beneath a lightweight waiting indicator. Several barriers can
        share the same elements. Keep it atomic, with one short trial
        or page per pass (the loop repeats it), such as
        "PageMaker(trial_maker.cue_trial, ...)" in the "sync_quorum"
        demo: a release then fails at most the trial on screen and
        creates no unseen trials (see "release_grace"). A barrier with
        "waiting_logic" can't be inside a trial's own pages, such as
        in "Trial.show_trial"; use "waiting_screen" there.

      * **waiting_logic_expected_repetitions** -- Deprecated; pass
        "expected_wait" instead. Expected repetitions of
        "waiting_logic".

      * **max_wait_time** -- The maximum amount of time in seconds
        that the participant will be allowed to wait at the barrier;
        if this time is exceeded then the participant will be failed
        and sent to the end of the experiment. May also be a function
        of "participant", evaluated once when the participant arrives.
        This is a hard limit counted from arrival: with explicit
        "waiting_logic", the server applies it even while the
        participant is partway through a filler page, so make it long
        enough to cover long filler pages (for example trials used as
        filler).

      * **fix_time_credit** -- If set to "True", award fixed expected
        time credit. Otherwise default holds credit actual visible
        waiting time up to "max_wait_time".

      * **expected_wait** -- Seconds participants are expected to wait
        here, used for progress estimates and fixed time credit.
        Default: 1.5 seconds. With "waiting_logic", the estimate is
        instead as many whole passes of the waiting logic as fill this
        time (at least one), or three passes if omitted.

      * **waiting_message** -- Message displayed by the default
        timeline hold overlay. Only used when "waiting_logic" is
        omitted. If omitted, participants see "Waiting for other
        participants…". Plain strings are shown as text; pass
        "markupsafe.Markup" or a dominate tag for HTML. On barriers
        with a release time ("SimpleGrouper" with "start_short_after",
        "Regrouper" with "deadline" or "every", or a subclass that
        overrides "expected_release_time()"), a "{SECONDS}"
        placeholder counts down to that time, showing "…" while it is
        unknown (a "SimpleGrouper" shows "Waiting for other
        participants…" instead until enough people wait to start
        short); elsewhere it raises an error. "waiting_message" can
        also be a module-level function that returns the message, for
        example one that depends on the participant's role; it may
        take "participant", "seconds_left" (whole seconds, or "None"
        while the release time is unknown) and "barrier", and on a
        "GroupBarrier" also "waiting_count" and "group_size" (both
        "None" if the participant has no group). It is called again
        whenever the release time changes, so for a live countdown
        return a literal ""{SECONDS}"" rather than formatting
        "seconds_left" into the text. Return "hold_message()" to set
        the progress line under the message yourself.

      * **waiting_screen** -- What to show in place of the current
        page while the participant waits: a prompt, text or HTML
        (shown without a Next button), or a "ModularPage" that nothing
        submits, for example with
        "NullControl(show_next_button=False)". Pass a module-level
        function to show each participant their own screen. It may
        take "participant", "trial" (their "current_trial", or "None")
        and "group_round" (that trial's "SyncGroupRound", or "None" if
        it is in no group's round), for example "waiting_screen(trial,
        group_round)" to show the player's answer and the round's
        state. At a grouper or "Regrouper", "trial" is the
        participant's previous trial, such as the previous round's,
        because "current_trial" only changes when the next trial is
        cued. It runs on each request (a page load or a check for the
        release), sometimes more than once, so base it on the
        participant's state rather than on chance. Returning "None"
        keeps the current page, as omitting "waiting_screen" does; if
        that page is another barrier's waiting screen, a plain waiting
        page replaces it. The "waiting_message" still shows on top. A
        page with a Next button, push buttons or "auto_advance", or
        one that needs a full page reload (for example deprecated
        "js_links") while "inplace_timeline_transitions" is on, raises
        "ValueError" when it is shown. Only used when "waiting_logic"
        is omitted.

      * **release_grace** ("Optional"["float"]) -- Seconds a
        participant on a "waiting_logic" page has to finish it once
        they are released; the page then ends without an answer,
        recorded with ""interrupted": True" in its response metadata.
        The rest of the participant's pass of "waiting_logic" is then
        run through without showing its pages (code blocks still run),
        and each "while_loop" in it ends at its next check. This
        includes the pages of trials in "waiting_logic", such as
        filler trials from a trial maker: a trial whose page ends this
        way, and any trial that the rest of the pass reaches, which is
        created but never shown, is failed with
        "failed_reason="interrupted_by_release"", so it isn't
        finalized, shows no feedback, and doesn't count towards the
        trial maker's targets of completed trials (it still counts
        towards "max_trials_per_block" and "n_created_trials"). "None"
        lets each waiting page run to its end. Default: 3 seconds.
        Only used with "waiting_logic"; passing it without raises an
        error.

   can_participant_exit(participant)

      Return whether the participant may leave "waiting_logic".

      Checks the "released" flag, because a link released earlier in
      the same request stays in "active_barriers" until it expires.

   check_waiting_participants(waiting_participants)

      Run any side-effecting checks before deciding who to release.

      Runs on the reconstructed registry barrier during evaluation.

   choose_who_to_release(waiting_participants)

      Given a list of waiting participants, decides which of these
      participants should be released from the barrier.

      Runs on the reconstructed registry barrier during evaluation.

      Parameters:
         **waiting_participants** ("List"["Participant"]) -- A list of
         waiting participants.

      Return type:
         "List"["Participant"]

      Returns:
         * *A list of participants to be released.*

   expected_release_time(participant)

      Return when this participant will be released at the latest, in
      epoch seconds.

      Used for the "{SECONDS}" countdown in "waiting_message". "None"
      (default) means the release time is unknown.

      Return type:
         "Optional"["float"]

   get_waiting_participants(participant=None, *, for_update=False)

      Return people currently waiting at this barrier visit.

      Pass "participant" to scope the list to that person's instance.
      Without one, this lists the pool of participants whose
      "waiting_pool_group()" is "None". Grouped barriers require a
      participant; see "GroupBarrier.get_waiting_participants()". This
      listing does not take extra row locks unless "for_update" is
      true.

      Parameters:
         * **participant** -- A waiter whose "active_barriers" link
           identifies the visit. Must be a participant, not a boolean;
           "for_update" is keyword-only.

         * **for_update** ("bool") -- Lock the waiter rows until the
           current transaction ends.

      Returns:
         Active, unreleased waiters at this visit.

      Return type:
         list of Participant

   handle_max_wait_timeout(participant)

      Release the participant's active barrier link after a max-wait
      timeout.

   receive_participant(participant)

      Register this participant on the live timeline barrier.

      Live timeline only. Default holds queue the release check from
      the hold page after the wait row exists.

   waiting_pool_group(participant)

      Return the group whose members wait together at this barrier, or
      "None".

      Each group gets its own waiting pool, with its own lock, so a
      busy member of one group never delays another group's release.
      "None" (default) puts everyone in one pool.

      Return type:
         "Optional"["SyncGroup"]

   would_release(waiting_participants)

      Return whether evaluating this visit would release anyone.

      "GET /timeline" uses this to decide whether to wait for the
      visit claim. It must not mutate participants, groups, or the
      session. Last-arrival skip-in-one-GET waits only when this is
      true. Custom barriers that override "choose_who_to_release()"
      should override this too. The default is "True" whenever anyone
      is waiting, so a missing override still waits rather than first-
      painting a hold.

      Return type:
         "bool"

class psynet.sync.BarrierDefinition(*args, **kwargs)

   Bases: "Base", "SQLMixin"

   Identify a public barrier waiting area without storing mutable
   visits.

   creation_time

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   classmethod ensure_exists(barrier_id, barrier_class)

      Register a definition in the caller's transaction.

   failed

      boolean indicating whether the Network has failed which prompts
      Dallinger to ignore it unless specified otherwise. Objects are
      usually failed to indicate something has gone wrong.

   failed_reason

      an optional reason the object was failed. If the object is
      failed as part of a cascading failure triggered from another
      object, the chain of objects will be captured in this field.

   id

      a unique number for every entry. 1, 2, 3 and so on...

   property1

      a generic column that can be used to store experiment-specific
      details in String form.

   property2

      a generic column that can be used to store experiment-specific
      details in String form.

   property3

      a generic column that can be used to store experiment-specific
      details in String form.

   property4

      a generic column that can be used to store experiment-specific
      details in String form.

   property5

      a generic column that can be used to store experiment-specific
      details in String form.

   time_of_death

      the time at which failing occurred

   type

   vars

class psynet.sync.BarrierInstance(*args, **kwargs)

   Bases: "Base", "SQLMixin"

   Persist one stable barrier behavior for a coordination visit.

   At most one active row exists per "(barrier_id, group_id)".
   Ungrouped barriers ("group_id" is null), including groupers, share
   one active waiting pool per barrier ID.

   creation_time

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   failed

      boolean indicating whether the Network has failed which prompts
      Dallinger to ignore it unless specified otherwise. Objects are
      usually failed to indicate something has gone wrong.

   failed_reason

      an optional reason the object was failed. If the object is
      failed as part of a cascading failure triggered from another
      object, the chain of objects will be captured in this field.

   classmethod for_arrival(barrier, participant)

      Return the stable instance that should receive this participant.

   get_barrier()

      Return the reconstructed release object for this visit.

      This is not the live timeline barrier. See "Barrier" for which
      methods are safe here. Reconstructions are memoized on the
      current SQLAlchemy session so grouped-page render does not re-
      parse the spec. The visit-claim peek drops that memo after it
      rolls back.

   id

      a unique number for every entry. 1, 2, 3 and so on...

   property1

      a generic column that can be used to store experiment-specific
      details in String form.

   property2

      a generic column that can be used to store experiment-specific
      details in String form.

   property3

      a generic column that can be used to store experiment-specific
      details in String form.

   property4

      a generic column that can be used to store experiment-specific
      details in String form.

   property5

      a generic column that can be used to store experiment-specific
      details in String form.

   time_of_death

      the time at which failing occurred

   type

   vars

class psynet.sync.GroupBarrier(id_, group_type, waiting_logic=None, waiting_logic_expected_repetitions=None, max_wait_time=<class 'psynet.utils.NoArgumentProvided'>, on_release=None, fix_time_credit=False, *, max_wait_action='fail', late_after=None, late_action=None, also_leave=None, expected_wait=None, waiting_message=None, on_arrival_message=<function default_group_barrier_arrival_message>, release_grace=<class 'psynet.utils.NoArgumentProvided'>, waiting_screen=None, stop_top_ups=False, admission_point=False, newcomer_max_wait=None, newcomer_page=None)

   Bases: "Barrier"

   A GroupBarrier is a Barrier that waits until all participants in a
   given "SyncGroup" have reached the Barrier. It also checks the
   group against its "quorum": a group below it can't proceed, and
   waits for newcomers or is dissolved (see Groups below quorum).

   It waits for every active member of the group, wherever they are in
   the timeline, until they leave the group: with "leave_group()",
   "late_action" or "max_wait_action", or by failing or finishing the
   experiment. So a member whose part ends before the group's, such as
   at the end of a loop that runs a different number of times for each
   member, must leave the group there (see After leaving a group).
   When every member it releases is inside the same round's trial of a
   "cue()" with "sync_group_type", that is, at a barrier in
   "show_trial", the release closes that round to newcomers, whose
   cues then start the next round. If every member is waiting but at
   different barriers of the group, none of them can ever pass: PsyNet
   records and logs an error naming the barriers, bot tests fail with
   it, and "late_after" or "max_wait_time" ends the wait (see members
   at different barriers).

   After the arrival write commits, the same request evaluates the
   barrier in a short transaction so partners are released without
   waiting for the 0.5 s poller. On the default hold path that arriver
   then skips their own wait indicator. Partners leave on overlay
   wake; the poller skips waiters only when it won the release.
   "on_release" receives the reconstructed registry barrier; see
   "Barrier" for the live-versus-reconstructed method split.

   A participant who was removed from their group of "group_type", for
   example by a timeout with ""leave_group"", and is in no other group
   of that type passes straight through, as does one whose grouper let
   them continue without a group
   ("max_wait_action="continue_without_group""). Any other participant
   who was never in such a group gets an error, which usually means a
   grouper is missing from the timeline.

   Parameters:
      * **id** -- ID parameter for the Barrier. Barriers with the same
        ID share waiting areas; this allows participants at different
        points in the timeline to share the same waiting areas.

      * **group_type** ("str") -- Identifies the kind of groups that
        the Barrier is operating over (see "Grouper").

      * **waiting_logic** -- Either a single timeline element or a
        list of timeline elements (created by "join") that is to be
        displayed to the participant while they are waiting at the
        barrier, for example filler trials. If left at "None", the
        participant sees "waiting_screen", or their current page
        beneath a lightweight waiting indicator. Pass
        "waiting_message" to customize that indicator's message. See
        "Barrier" for where "waiting_logic" can go.

      * **waiting_logic_expected_repetitions** -- Deprecated; pass
        "expected_wait" instead. Expected repetitions of
        "waiting_logic".

      * **max_wait_time** ("Union"["float", "Callable", "None"]) --
        Acts on members waiting at this barrier: the longest each may
        wait, in seconds, counted from their arrival, before
        "max_wait_action" is applied to them. Defaults to 20 seconds,
        or to no limit with "late_after", which then moves slow
        members on; passing a number or a function together with
        "late_after" raises an error, because a limit fixed at each
        arrival can't know how long a slower member's timed page still
        runs, and could time out the members who were on time before
        "late_after" frees them. "None" means no limit. May also be a
        function of "participant", evaluated once when they arrive.
        This is a hard limit counted from arrival: with explicit
        "waiting_logic", the server applies it even while the
        participant is partway through a filler page, so make it long
        enough to cover long filler pages (for example trials used as
        filler).

      * **max_wait_action** ("Literal"["'fail'", "'leave_group'"]) --
        What happens to a member who waits longer than
        "max_wait_time". Either way they first leave the group, which
        records ""waited_too_long"" as their removal reason and,
        unless a release has already made it ""stayed"", the
        "sync_group_outcome" of their trial in the group's round.
        ""fail"" (default) then fails them, after they leave their
        other groups as ""left_experiment"", and sends them to the end
        of the experiment; with ""leave_group"" they carry on with the
        experiment without the group (see After leaving a group). With
        ""leave_group"", their next page says "Your partner didn't
        arrive in time. Please continue." in a pair (see
        "on_arrival_message" for larger groups); for how a
        "GroupPrompt" shows them, see Showing the group. It is the
        waiting member who leaves, not the absent ones; to move on
        without slow members, use "late_after" and "late_action"
        instead. If that takes the group below its quorum, see Groups
        below quorum for whether it is dissolved.

      * **late_after** ("Optional"["float"]) -- Acts on members who
        haven't reached this barrier yet: the longest each may take to
        reach it, in seconds, counted from the group's previous
        barrier pass or from when the group admitted them, whichever
        is later, before "late_action" is applied to them; pending
        members are never late, and nobody is late while only pending
        members wait here. "None" (default) never treats anyone as
        late. A member on a page with a "time_limit" is never late
        before that limit has run out plus 10 seconds, so that an
        answer sent at the deadline can arrive; this timeout therefore
        need not cover the pages' time limits. Requires "late_action",
        and the grouper of "group_type" (and of each type in
        "also_leave") must then be given "below_quorum", which is
        checked when the experiment loads.

      * **late_action** ("Optional"["Literal"["'fail'",
        "'leave_group'"]]) -- What happens to a member who is later
        than "late_after", which requires it: ""fail"" fails them and
        sends them to the end of the experiment; ""leave_group""
        removes them from the group, so the rest can go on without
        them (see After leaving a group for what the removed member
        sees). ""leave_group"" can't be combined with a grouper's
        "below_quorum="fail"", which would fail the members who were
        on time while the late one carries on; the experiment raises
        an error at load, or when a trial shows a barrier built in
        "show_trial". With every action the member leaves this
        barrier's group with the reason ""late"" (with ""fail"",
        before they are failed), which their trial in the group's
        round records in "sync_group_outcome" unless an earlier
        barrier in the trial's pages already released the group with
        them in it (then it stays ""stayed""). A group without top-ups
        that this leaves below its quorum dissolves as its
        "below_quorum" says, so with "late_action="fail"" and
        "below_quorum="fail"" one late member can fail a whole cohort
        (see Groups below quorum for groups that accept top-ups).
        Removal is all or nothing: while a late member's own request
        is in progress, for example submitting a page, no late member
        of the group is acted on until a check finds none of them
        busy, usually the next one, so the removal can come a check
        later; if that request brought them to this barrier, they are
        no longer late. So code a late member runs in their own
        request, such as a "CodeBlock" storing their answer, either
        runs before the removal or sees it
        ("participant.sync_group_removal_reason", or, before the
        round's first release, their trial's "sync_group_outcome").

      * **also_leave** ("Optional"["Sequence"["str"]]) -- With
        "late_action="leave_group"", the other group types a late
        member also leaves, with the reason ""late"", for example
        "["cohort"]" for the cohort a pair was formed in, so that the
        cohort doesn't wait for them either. Their groups of other
        types keep them. "None" (default) leaves only this barrier's
        group.

      * **on_release** ("Optional"["Callable"]) --

        Optional callback invoked when the barrier releases the group.
        It may take "group", "participants" (the members it releases:
        the group's active members), "trials" (each member's
        "current_trial", in the same order as "participants", for
        example the trials of a "cue()" with "sync_group_type" that
        the barrier is part of), "group_round" (the "SyncGroupRound"
        whose trial every released member is in, or "None"; see the
        barrier's round), "leader" (the group's leader), "participant"
        (the same object as "leader", kept for compatibility), "left"
        (the members who left the group since its previous barrier
        pass, or since it formed; see below), "admitted" (the pending
        members an admission point admits with this release; see
        Admission points) and "barrier", the reconstructed registry
        object for this visit (scalar presentation and notification
        settings, not wait pages).
        "participant.sync_group_removal_reason(group_type)" says why
        each member in "left" went, for example to tell a player whose
        partner returned the study apart from one whose partner was
        too slow:

           def score_round(participants, left, barrier):
               for participant in left:
                   reason = participant.sync_group_removal_reason("pair")
                   ...

        Must be a module-level function,
        "@staticmethod"/"@classmethod", or a bound method on a
        TrialMaker or ORM instance with a primary key. To share one
        callback between several barriers, give each its own arguments
        with "functools.partial()", passed by keyword and JSON-
        compatible, for example the number of the question the barrier
        ends:

           def score_question(group, question):
               ...

           GroupBarrier(id_="question_1", group_type="team",
                        on_release=partial(score_question, question=1))

        Barriers that share an "id_" must pass the same arguments.

      * **stop_top_ups** ("bool") -- If "True", the group stops
        accepting newcomers once it passes this barrier, as
        "SimpleSyncGroup.stop_top_ups()" does, for example at the
        barrier that starts a game, so nobody joins it once it is
        under way. Only affects groups formed with
        "join_existing_groups=True". A group below its quorum doesn't
        pass, so it keeps waiting here for a newcomer, up to the
        grouper's "top_up_wait", if set (see Groups below quorum). A
        group whose grouper has "use_admission_points=True" waits only
        if this barrier is an admission point; otherwise it is
        dissolved. Pending members are turned away as
        ""not_admitted""; at an admission point, those waiting here
        are admitted first.

      * **admission_point** ("bool") -- If "True", this barrier admits
        the group's pending members (see
        "SimpleGrouper(use_admission_points=True)"): they wait here,
        and its release admits them, in the order they joined,
        together with the group, which counts them towards its
        "quorum" and waits up to "top_up_wait" for newcomers while it
        has fewer members than the grouper's "target_group_size".
        Pending members pass every other barrier straight through. Put
        it where a newcomer can sensibly start, such as the start of a
        round or generation. See Admission points.

      * **newcomer_max_wait** ("Optional"["float"]) -- Required with
        "admission_point=True": the longest a pending member may wait
        for this admission point, in seconds, counted from when they
        joined the group. It replaces "max_wait_time" for them. Once
        it runs out they are turned away: they leave the group as
        ""not_admitted"", are never failed, carry on past the group's
        barriers like any member who left it, and see the
        "on_arrival_message" notice of kind ""not_admitted"" on their
        next page.

      * **newcomer_page** -- Optional page, page maker or list of
        timeline elements shown right after this admission point only
        to the members it just admitted, for example a summary of the
        group's history.

      * **fix_time_credit** -- If set to "True", award fixed expected
        time credit. Otherwise default holds credit actual visible
        waiting time up to "max_wait_time".

      * **expected_wait** -- See "Barrier".

      * **waiting_message** -- Message displayed by the default
        timeline hold overlay. Only used when "waiting_logic" is
        omitted. If omitted, participants see "Waiting for other
        participants…". Plain strings are shown as text; pass
        "markupsafe.Markup" or a dominate tag for HTML, or a module-
        level function "waiting_message(participant)" returning either
        (see "Barrier"). Independent of a preceding "Grouper"'s
        "waiting_message" and of trial-maker
        "sync_group_waiting_message".

      * **release_grace** ("Optional"["float"]) -- See "Barrier".
        Default: 3 seconds.

      * **waiting_screen** -- See "Barrier".

      * **on_arrival_message** ("Optional"["Callable"]) --

        Callable that returns arrival copy for one participant, by
        default "default_group_barrier_arrival_message()". It receives
        "kind" (""notice"", ""late"", ""waited_too_long"" or
        ""not_admitted""), "waiting_count", "group_size", and the
        usual context arguments ("participant", the one who sees the
        copy, "group", "barrier", "experiment"). Return "None" to hide
        that notice. Same serialization rules as "on_release". Pass
        "on_arrival_message=None" to turn off all of this barrier's
        arrival notices, including the not-ready count on the waiting
        indicator in groups of three or more. To change the waiting
        indicator's progress line instead, return "hold_message()"
        from a "waiting_message" function.

        ""notice"" is the progress-bar notice for members who have not
        reached the barrier yet. It defaults to "Your partner is
        ready." in pairs and ""{ARRIVED}/{TOTAL} of your group are
        ready."" in larger groups. It is called whenever the
        participant's browser fetches its notice, which can be several
        times per arrival, so it should depend only on its arguments
        and have no side effects. Notices wrap onto at most two lines
        (overflow ellipsizes), so keep them to a short sentence.

        ""late"" is the progress-bar notice for someone removed by
        "late_action="leave_group"", shown until they leave their
        page. It defaults to "Your partner went on without you. Please
        continue." or "Your group went on without you. Please
        continue.", and "group_size" counts the group before anyone
        was removed.

        ""waited_too_long"" is the notice for someone removed by
        "max_wait_action="leave_group"", shown on the page they move
        on to. It defaults to "Your partner didn't arrive in time.
        Please continue." or "Not everyone in your group arrived in
        time. Please continue.".

        ""not_admitted"" is the notice for a pending member turned
        away before an admission point admitted them (see
        "newcomer_max_wait"), shown on the page they move on to. It
        defaults to "We couldn't add you to a group in time. Please
        continue.".

        Check "kind" for each of these rather than treating everything
        that isn't ""late"" as a progress notice, or a removed member
        sees "Your partner is ready." after waiting too long.

   check_waiting_participants(waiting_participants)

      Remove members late between barriers; relies on the lock taken
      in "_lock_top_up_groups()".

   choose_who_to_release(waiting_participants)

      Release each waiting group that is ready, and dissolve those
      that can't reach their quorum.

      Expects to run inside a barrier check, which has locked the
      waiters and their groups that accept top-ups; called directly,
      it counts the members this session has loaded and takes no such
      locks.

   get_waiting_participants(participant=None, *, for_update=False)

      Return people waiting at this group visit.

      Grouped barriers have no ungrouped pool, so "participant" is
      required to identify the visit. Use the visit link
      "participant.active_barriers[...].get_waiting_participants()"
      when you already have it.

   handle_max_wait_timeout(participant)

      Remove the waiter from the sync group as ""waited_too_long"",
      then release the barrier link.

      With "max_wait_action="fail"" the waiter also leaves their other
      groups as ""left_experiment"" and is failed as a timeout before
      any quorum is checked, as in "_remove_late_participants()", so a
      group dissolving cannot fail them for its own reason first.

   waiting_pool_group(participant)

      Return the participant's group of "group_type"; its members wait
      together.

      Return type:
         "SyncGroup"

   would_release(waiting_participants)

      Return whether this group visit would release, without mutating
      state.

      Mirrors "check_waiting_participants()" followed by
      "choose_who_to_release()": late members that the between-barrier
      timeout would remove or fail count as already gone, and group
      size is recounted rather than read from "n_active_participants".

      Return type:
         "bool"

class psynet.sync.GroupCloser(group_type, **kwargs)

   Bases: "GroupBarrier"

   A timeline construct for closing a previously created group. This
   is required before creating a new group with the same "group_type".

exception psynet.sync.GroupDivergenceError

   Bases: "RuntimeError"

   A group's members wait for each other at different group barriers,
   so none can pass.

   "check_barriers()" records it as an "ErrorRecord" and logs it (see
   members at different barriers); bot tests then fail with it (see
   "fail_on_group_divergence()").

class psynet.sync.Grouper(group_type, id_=None, waiting_logic=None, waiting_logic_expected_repetitions=None, max_wait_time=20, expected_wait=None, fix_time_credit=False, waiting_message=None, release_grace=<class 'psynet.utils.NoArgumentProvided'>, waiting_screen=None, *, max_wait_action='fail')

   Bases: "Barrier"

   A Grouper is a kind of Barrier that assigns incoming participants
   into groups. This is a generic class whose subclasses must override
   several methods, in particular "ready_to_group" and "group".

   Parameters:
      * **group_type** ("str") -- A textual label for the groups that
        are created. This label is used to link the Grouper with
        subsequent GroupBarriers.

      * **id** -- Optional ID parameter for this grouper. If left
        blank the default value is "group_type + "_" + "grouper"".
        Groupers with the same ID are treated as equivalent and share
        the same participant waiting areas.

      * **waiting_logic** -- Either a single timeline element or a
        list of timeline elements (created by "join") that is to be
        displayed to the participant while they are waiting at the
        barrier, for example filler trials. If left at "None", the
        participant sees "waiting_screen", or their current page
        beneath a lightweight waiting indicator. See "Barrier" for
        where "waiting_logic" can go.

      * **waiting_logic_expected_repetitions** -- Deprecated; pass
        "expected_wait" instead. Expected repetitions of
        "waiting_logic".

      * **max_wait_time** -- The maximum amount of time in seconds
        that the participant will be allowed to wait at the barrier;
        if this time is exceeded and the participant is still not
        released, then "max_wait_action" is applied to them. This is a
        hard limit counted from arrival: with explicit
        "waiting_logic", the server applies it even while the
        participant is partway through a filler page, so make it long
        enough to cover long filler pages (for example trials used as
        filler).

      * **max_wait_action** ("Literal"["'fail'",
        "'continue_without_group'"]) -- What happens to a participant
        who waits longer than "max_wait_time" without being grouped:
        ""fail"" (default) fails them and sends them to the end of the
        experiment; ""continue_without_group"" lets them carry on with
        the experiment without a group, which suits a participant who
        was available but couldn't be matched. Their next page says
        "We couldn't find a partner for you in time. Please continue."
        (or "...a group for you..."). Later barriers and synchronized
        trial makers of this group type treat them as having left a
        group (see After leaving a group), and
        "sync_group_removal_reason()" returns ""no_group_formed"".
        Branch on "participant.in_sync_group(group_type)" to give them
        something else to do or to end the experiment.

      * **expected_wait** -- See "Barrier".

      * **waiting_message** -- Message displayed by the default
        timeline hold overlay. Only used when "waiting_logic" is
        omitted. Plain strings are shown as text; pass
        "markupsafe.Markup" or a dominate tag for HTML. This Grouper's
        overlay is independent of trial-maker
        "sync_group_waiting_message"; pass "waiting_message" here and
        on later "GroupBarrier" waits if they should match. Can be a
        function of "seconds_left", as for "Barrier".

      * **fix_time_credit** -- If "True", award fixed "expected_wait"
        credit instead of actual visible waiting time.

      * **release_grace** ("Optional"["float"]) -- See "Barrier".
        Default: 3 seconds.

      * **waiting_screen** -- See "Barrier".

   choose_who_to_release(waiting_participants)

      Given a list of waiting participants, decides which of these
      participants should be released from the barrier.

      Runs on the reconstructed registry barrier during evaluation.

      Parameters:
         **waiting_participants** ("List"["Participant"]) -- A list of
         waiting participants.

      Returns:
         * *A list of participants to be released.*

   group(participants)

      This method is run if "ready_to_group" returns "True". It is
      responsible for grouping participants.

      Parameters:
         **participants** ("List"["Participant"]) -- Participants who
         are candidates for grouping.

      Return type:
         A list of SyncGroups who should be populated by the grouped
         participants.

   handle_max_wait_timeout(participant)

      Let an ungrouped participant carry on with
      ""continue_without_group"", then release the barrier link.

   ready_to_group(participants)

      Determines whether the Grouper is ready to group a given
      collection of participants. Note that not all participants need
      to be grouped at once; it's permissible to leave some
      participants still waiting.

      Parameters:
         **participants** ("List"["Participant"]) -- List of
         participants who are candidates for grouping.

      Return type:
         "bool"

      Returns:
         * "True" if the grouper is ready to group (some of) the
           participants, "False" otherwise.

   receive_participant(participant)

      Register this participant on the live timeline barrier.

      Live timeline only. Default holds queue the release check from
      the hold page after the wait row exists.

   select_leader(participants)

      By default the leader is randomly chosen from the list of
      available participants.

      Parameters:
         **participants** ("List"["Participant"]) -- Participants to
         choose from.

      Return type:
         "Participant"

      Returns:
         * *A participant to be assigned 'leader' of the SyncGroup.*

   would_release(waiting_participants)

      Return whether this grouper would form groups, without creating
      them.

      Return type:
         "bool"

psynet.sync.INTERRUPTED_BY_RELEASE = 'interrupted_by_release'

   "failed_reason" of a trial whose page a barrier's release ended
   before it was answered.

psynet.sync.LateAction

   What a "GroupBarrier" does with a member who is late reaching it;
   see "late_action".

   alias of "Literal"['fail', 'leave_group']

class psynet.sync.ParticipantLinkBarrier(*args, **kwargs)

   Bases: "Base", "SQLMixin"

   creation_time

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   failed

      boolean indicating whether the Network has failed which prompts
      Dallinger to ignore it unless specified otherwise. Objects are
      usually failed to indicate something has gone wrong.

   failed_reason

      an optional reason the object was failed. If the object is
      failed as part of a cascading failure triggered from another
      object, the chain of objects will be captured in this field.

   get_waiting_participants(*, for_update=False)

      Return people waiting at this visit.

      Does not take extra row locks unless "for_update" is true.
      "for_update" is keyword-only, matching
      "Barrier.get_waiting_participants()".

   id

      a unique number for every entry. 1, 2, 3 and so on...

   property1

      a generic column that can be used to store experiment-specific
      details in String form.

   property2

      a generic column that can be used to store experiment-specific
      details in String form.

   property3

      a generic column that can be used to store experiment-specific
      details in String form.

   property4

      a generic column that can be used to store experiment-specific
      details in String form.

   property5

      a generic column that can be used to store experiment-specific
      details in String form.

   ran_out_of_time

      the last page the participant answered before arriving, other
      than a waiting page, ended on its time limit
      ("Participant.timed_out_since_barrier"). It drives the "ran out
      of time" mark of "GroupPrompt". To analyse time-outs, read
      "psynet.trial.main.Trial.time_limit_reached" or
      "psynet.timeline.Response.time_limit_reached" instead.

      Type:
         Internal

   time_of_death

      the time at which failing occurred

   type

   vars

class psynet.sync.ParticipantLinkSyncGroup(*args, **kwargs)

   Bases: "Base", "SQLMixin"

   admission_points_passed

      How many of the group's admission points released the member
      once admitted, counting the one that admitted them.

   admitted_at

      at formation, on joining with "use_admission_points=False", or
      at an admission point. "None" while they are pending (see
      "SyncGroup.pending_participants").

      Type:
         When the group took the member in

   creation_time

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   failed

      boolean indicating whether the Network has failed which prompts
      Dallinger to ignore it unless specified otherwise. Objects are
      usually failed to indicate something has gone wrong.

   failed_reason

      an optional reason the object was failed. If the object is
      failed as part of a cascading failure triggered from another
      object, the chain of objects will be captured in this field.

   id

      a unique number for every entry. 1, 2, 3 and so on...

   property1

      a generic column that can be used to store experiment-specific
      details in String form.

   property2

      a generic column that can be used to store experiment-specific
      details in String form.

   property3

      a generic column that can be used to store experiment-specific
      details in String form.

   property4

      a generic column that can be used to store experiment-specific
      details in String form.

   property5

      a generic column that can be used to store experiment-specific
      details in String form.

   time_of_death

      the time at which failing occurred

   type

   vars

class psynet.sync.Regrouper(group_type, *, within=None, group_size=None, smallest_group=None, deadline=None, every=None, roles=None, form_groups=None, assign_roles=None, left_over='wait', on_release=None, stop_top_ups_after_rounds=None, max_wait_time=<class 'psynet.utils.NoArgumentProvided'>, **kwargs)

   Bases: "Grouper"

   Repeatedly split participants into new groups, for example once per
   round.

   Each time a participant reaches the regrouper, they leave their
   previous group of this "group_type" and wait for the next split.
   Waiting participants are pooled: by default everyone waiting is one
   pool, and with "within" each existing group (such as a cohort) is
   its own pool. A pool is split into groups when every active member
   of its "within" group is waiting, or when its "deadline" passes,
   whichever comes first. With "every", splits happen only on fixed
   wall-clock ticks instead. Absent members are not waited for beyond
   the deadline once a group can be formed without them, and are never
   failed for missing a split; they join the pool again when they come
   back.

   Groups made by a regrouper don't accept top-ups and are never
   dissolved when a member leaves, so a member who drops out of a
   round leaves their partners in a smaller group rather than failing
   them.

   By default, members are grouped at random, and when not everyone
   waiting fits into a group, those who have played the most rounds
   sit out. The regrouper counts each participant's rounds
   ("rounds_played()", "rounds_sat_out()", "sat_out()") and, with
   "roles", gives out roles (read in a cued trial as
   "sync_group_role"), all while it holds its lock, so two splits
   cannot give out the same seat twice. Each group records the
   regrouper that formed it, and each member's link to it records
   their role, so these counts come from the groups themselves.

   Parameters:
      * **group_type** ("str") -- Type of the groups this regrouper
        creates, for example ""pair"".

      * **within** ("Optional"["str"]) -- Optional "group_type" of an
        existing group to regroup within, for example ""cohort"".
        Participants are only grouped with members of the same
        "within" group, and a pool counts as complete once all that
        group's admitted members are waiting. A participant without
        such a group is released ungrouped. If "None" (default),
        everyone waiting is one pool, which is only split at the
        "deadline" or "every" tick. Each split is an admission point
        of the "within" group (see Admission points): its pending
        members waiting in the pool are admitted, then grouped with
        the rest.

      * **group_size** ("Optional"["int"]) -- Size of the groups to
        form. The pool is split into balanced groups of at most this
        size, for example rooms of 8, 8, 7 and 7 for 30 people with
        "group_size=8". Required unless "roles" is given, which sets
        it.

      * **smallest_group** ("Optional"["int"]) -- Smallest group to
        form when the pool doesn't divide evenly or members are
        missing: 2 by default (or "group_size" if that is smaller). A
        pool is only split once this many of its members are waiting.
        Groups are never dissolved later, so a group can carry on
        below this size. With "roles" every group has one member per
        role.

      * **deadline** ("Optional"["float"]) -- Seconds to wait for
        absent members, counted from when the first of the pool's
        waiting members arrived, or from the pool's previous split if
        that is later. The pool is split when it is complete or when
        the deadline passes. Make it longer than a round takes:
        otherwise members who finish a round early are split again
        before the rest are back. "None" (default) waits until the
        pool is complete, which needs "within".

      * **every** ("Optional"["float"]) -- Seconds between fixed wall-
        clock ticks. The pool is split only at a tick, even when
        everyone is already waiting, if at least "smallest_group"
        members were waiting at the tick. The background barrier check
        makes the split at its next check after the tick, normally
        within a second, so participants arriving with Next don't wait
        for a check of the whole pool; an arrival or reload in "GET
        /timeline" still checks the waiter's visit. Pass either
        "deadline" or "every", not both.

      * **roles** ("Optional"["Sequence"["str"]]) -- Optional role
        names, for example "["proposer", "responder"]". Each group
        then has one member per role, so groups have "len(roles)"
        members; "group_size", if given, must equal it. A cued trial
        reads its player's role as "sync_group_role". Roles are given
        out at random by default; see "assign_roles".

      * **form_groups** ("Optional"["Callable"]) -- Optional callable
        "form_groups(members, within_group, barrier)" that returns a
        list of groups, each a list of participants, replacing the
        default grouping described above; "barrier" is this regrouper.
        Members who are not placed are left over. With "roles", each
        group needs one member per role; "assign_roles" then gives out
        the roles. Subclasses can override "form_groups()" instead,
        for example calling the default and retrying until no one is
        paired with last round's partner, as the "ultimatum_pairing"
        demo does. The callable must be a module-level function so it
        can be stored with the barrier.

      * **assign_roles** ("Optional"["Callable"]) -- Optional callable
        "assign_roles(members, within_group, barrier)" that returns
        "{participant: role}" for one group formed with "roles",
        giving each role to one member; "barrier" is this regrouper.
        It is called once per group, before the group is created,
        replacing the default, which shuffles the roles across the
        group's members. Subclasses can override "assign_roles()"
        instead, for example to give each role to whoever has held it
        least often, so that roles alternate, as the
        "ultimatum_pairing" demo does. The callable must be a module-
        level function so it can be stored with the barrier.

      * **left_over** ("Literal"["'wait'", "'sit_out'"]) -- What
        participants left over after a split do: ""wait"" (default)
        keeps them waiting for the next split, and ""sit_out"" lets
        them continue ungrouped, for example to a sit-out page, and
        come back for the next split. With "within", when too few are
        waiting to form any group, for example one player whose cohort
        is still playing a round, they wait for the rest of the cohort
        for up to one more "deadline" (or "every" tick) before they
        are released ungrouped, or until "max_wait_time" if there is
        no deadline. Taking members who stop playing out of the
        "within" group, for example with "remove_participant", means
        nobody waits for them.

      * **on_release** ("Optional"["Callable"]) -- Optional callback
        "on_release(within_group, groups, left_over, barrier)" run
        after each split that forms at least one group, after roles
        are given out; "barrier" is this regrouper. The new "groups"
        already have their "id", for example to save as a pair ID. A
        late member can make a split of their own in the same round,
        so count rounds per participant (see "rounds_played()") rather
        than here.

      * **stop_top_ups_after_rounds** ("Optional"["int"]) -- Optional
        number of rounds during which newcomers can still join the
        "within" group, for example a cohort formed with
        "join_existing_groups=True". Each split that forms groups in
        the cohort counts as one of its rounds, even one that groups
        only latecomers while the others are still playing. The next
        split, even one in which everyone waiting sits out, stops the
        cohort's top-ups, as "SimpleSyncGroup.stop_top_ups()" does; a
        cohort below its quorum is then dissolved instead of split, as
        its "below_quorum" says. With "0" the cohort closes when its
        first round starts. "None" (default) leaves top-ups to the
        grouper and the barriers. Needs "within", and only applies to
        "within" groups that accept top-ups; it does nothing for
        others.

      * **max_wait_time** ("Union"["float", "Callable", "None"]) --
        Longest a participant waits at the regrouper before
        "max_wait_action" applies: being failed by default, or
        carrying on without a group with
        "max_wait_action="continue_without_group"". Defaults to 300
        seconds, or to twice the "deadline" (or "every" period) plus
        60 seconds if that is longer. With "left_over="sit_out"" and
        "within", a value you pass must be longer than twice the
        period, so that a player waiting alone sits out instead of
        being failed.

      * **waiting_message** -- Message shown while waiting. A
        "{SECONDS}" placeholder becomes a live countdown to the pool's
        deadline or next tick, for example ""Next round in {SECONDS}
        s"". To show other text while the deadline is unknown, for
        example while a participant waits alone, pass a function of
        "seconds_left", which is "None" then (see "Barrier").

      * **kwargs** -- Further arguments to pass to "Grouper".

   assign_roles(members, within_group=None)

      Return "{participant: role}" for one group's members, one member
      per role.

      By default the roles are shuffled across the members.

      Return type:
         "Dict"["Participant", "str"]

   choose_who_to_release(waiting_participants)

      Given a list of waiting participants, decides which of these
      participants should be released from the barrier.

      Runs on the reconstructed registry barrier during evaluation.

      Parameters:
         **waiting_participants** ("List"["Participant"]) -- A list of
         waiting participants.

      Returns:
         * *A list of participants to be released.*

   expected_release_time(participant)

      Return when this participant's pool will be split at the latest,
      in epoch seconds.

      Return type:
         "Optional"["float"]

   form_groups(members, within_group=None)

      Return the groups to form from one pool's waiting members.

      By default members are shuffled into balanced groups of at most
      "group_size" and at least "smallest_group", or into one group
      per set of "roles". Those who have played the most rounds sit
      out.

   receive_participant(participant)

      Register this participant on the live timeline barrier.

      Live timeline only. Default holds queue the release check from
      the hold page after the wait row exists.

   rounds_played(participant)

      Return how many groups this regrouper has put "participant" in.

      A group counts from when it is formed, even if the participant
      is later removed from it, for example for being away too long.

      Return type:
         "int"

   rounds_sat_out(participant)

      Return how often "participant" sat a round out (see
      "left_over").

      Return type:
         "int"

   sat_out(participant)

      Return whether "participant" sat out their latest visit here
      (see "left_over").

      Return type:
         "bool"

   waiting_pool_group(participant)

      Return the participant's "within" group, so each cohort waits in
      its own pool.

      Return type:
         "Optional"["SyncGroup"]

   would_release(waiting_participants)

      Return whether this grouper would form groups, without creating
      them.

      Return type:
         "bool"

psynet.sync.RemovalReason

   Why a member left a group, see "SyncGroup.remove_participant()".

   alias of "Literal"['removed_by_experimenter', 'left_experiment',
   'late', 'waited_too_long', 'group_dissolved', 'moved_on',
   'finished', 'not_admitted']

class psynet.sync.SimpleGrouper(group_type, *, initial_group_size=None, max_group_size='initial_group_size', min_group_size=<class 'psynet.utils.NoArgumentProvided'>, batch_size='initial_group_size', join_existing_groups=False, join_criterion=None, below_quorum=None, start_short_after=None, start_short_with=None, quorum=None, top_up_wait=None, use_admission_points=None, target_group_size=None, max_groups=None, **kwargs)

   Bases: "Grouper"

   A Simple Grouper waits until "batch_size" many participants are
   waiting, and then randomly partitions this group of participants
   into groups of size "initial_group_size".

   Parameters:
      * **group_type** ("str") -- A textual label for the groups that
        are created. This label is used to link the Grouper with
        subsequent GroupBarriers.

      * **initial_group_size** ("Optional"["int"]) -- Size of the
        groups to create. The default barrier ID is
        "{group_type}_grouper_{initial_group_size}", so sequential
        groupers of different sizes do not share a waiting pool. Pass
        "id_" only when two groupers should share one pool and have
        the same release behavior.

      * **max_group_size** ("Union"["int", "str", "None"]) -- If
        "join_existing_groups=True", then participants will be allowed
        to join groups until they reach this maximum size. If set to
        ""initial_group_size"" (default), then the maximum size will
        be set to the initial group size.

      * **quorum** ("Optional"["int"]) -- How many active members a
        group needs to keep going. A group whose members fail or leave
        until it has fewer than this is below quorum; it then waits
        for newcomers or is dissolved (see Groups below quorum).
        Defaults to "start_short_with" if given, and otherwise to
        "initial_group_size", so that a group needs all its members;
        for groups of three or more, leaving it out warns. Must be at
        most "start_short_with" when that is set.

      * **min_group_size** ("Union"["int", "str"]) -- Deprecated name
        for "quorum".

      * **batch_size** ("Union"["int", "str"]) -- Number of
        participants that should be waiting until the groups are
        created. If set to ""initial_group_size"" (default), then the
        batch size will be set to the initial group size.

      * **join_existing_groups** ("bool") -- If set to "True", then
        before a new group is created, the Grouper will check if there
        are any existing groups that aren't full (e.g. because some
        participants left the experiment early). If so, the arriving
        participant will be assigned to one of these groups instead.
        Participants already waiting at the grouper join such a group
        on the next barrier check. Groups that have closed or stopped
        accepting top-ups, and groups with no active members, are not
        joined. Groups keep accepting top-ups until you stop them (see
        Groups below quorum). This behavior can be further customized
        via the "join_criterion" argument. Pass "use_admission_points"
        to say when such a newcomer starts taking part.

      * **use_admission_points** ("Optional"["bool"]) -- When a
        newcomer who joins an existing group starts taking part in it.
        "False" admits them at once, so the group's next barrier waits
        for them, which suits groups that only take newcomers before
        play starts (for example in a lobby closed by
        "stop_top_ups=True"). "True" makes them a pending member: they
        hold a seat, but barriers, the quorum, the leader and
        "GroupPrompt" ignore them until the group's next admission
        point (a "GroupBarrier(admission_point=True)", a synchronized
        trial maker's trial preparation, or a "Regrouper" with
        "within") admits them; they pass its other barriers straight
        through. See Admission points. Required with
        "join_existing_groups=True"; leaving it out warns and uses
        "False".

      * **target_group_size** ("Optional"["int"]) -- With
        "use_admission_points=True", which requires it, how many
        members the group tries to have: an admission point that would
        leave it with fewer admitted members waits up to "top_up_wait"
        for newcomers (without a limit if "top_up_wait" is "None"),
        then carries on with whoever is there as long as they meet the
        "quorum". Must be between "quorum" and "max_group_size"; set
        it to the "quorum" to carry on without waiting.

      * **max_groups** ("Optional"["int"]) -- Optional cap on how many
        of this grouper's groups may be active at once. Once it is
        reached, participants wait at the grouper for a seat in an
        existing group instead of forming a new one, for example to
        run a single society that newcomers join one by one. "None"
        (default) has no cap.

      * **join_criterion** ("Optional"["Callable"]) -- A callable that
        takes "group" and "participant" as arguments, and returns
        "True" if the participant should be allowed to join the group,
        and "False" otherwise. To be used in conjunction with
        "join_existing_groups=True". Returning "False" only turns that
        newcomer away; the group keeps accepting top-ups (see Groups
        below quorum).

      * **below_quorum** ("Optional"["str"]) -- What happens to the
        members left when a group is dissolved below its "quorum" (for
        when that happens, see Groups below quorum). The member whose
        departure caused it is handled by their own cause instead (a
        barrier's "max_wait_action" or "late_action", or their
        failure). ""fail"" fails them, telling them "Too few members
        of your group remained to continue, so we ended your session."
        ""continue_without_group"" lets them carry on with the
        experiment without the group, and their next page says that
        their group ended (see After leaving a group). With ""fail"",
        one member who is late or leaves can end the session of
        everyone who was on time, as in a pair. Required when the
        groups are designed to shrink: when "quorum" is below
        "initial_group_size", or when a "GroupBarrier" of this group
        type in the timeline has "late_after" (checked when the
        experiment loads). Otherwise it defaults to ""fail"". A
        barrier's "late_action="leave_group"" needs
        ""continue_without_group"". See Groups below quorum for when
        the group is dissolved.

      * **top_up_wait** ("Optional"["float"]) -- With
        "join_existing_groups=True", how many seconds a group below
        its "quorum" waits for newcomers. Then the next check of the
        "GroupBarrier" its members are waiting at stops top-ups and
        dissolves it; until all its remaining members have reached
        such a barrier, the group keeps accepting top-ups. The time
        counts from when the last of them arrived there, or from when
        the group fell below its quorum, if later. "max_wait_time"
        counts from each member's own arrival, so the first to arrive
        also waits for the others: give the barrier "late_after",
        which removes that limit, or a "max_wait_time" longer than
        "top_up_wait" plus the time members may take to reach it (see
        Groups below quorum). Default: "None", waiting for newcomers
        without a limit. Required (checked when the experiment loads,
        or when a trial shows a barrier built in "show_trial") if the
        groups could wait for newcomers at a barrier with
        "late_after": any of the group type's such barriers with
        "use_admission_points=False", or its admission points with
        "use_admission_points=True", unless an earlier barrier has
        "stop_top_ups=True".

      * **start_short_after** ("Optional"["float"]) -- If set, a group
        may start with fewer than "batch_size" participants once the
        longest-waiting participant has waited this many seconds and
        at least "start_short_with" participants are waiting. If fewer
        than "initial_group_size" are waiting, they form one smaller
        group. Requires "quorum" or "start_short_with", and a
        "max_wait_time" longer than "start_short_after" (not checked
        when "max_wait_time" is a function). Default: "None" (always
        wait for "batch_size").

      * **start_short_with** ("Optional"["int"]) -- The smallest group
        that "start_short_after" may start, between 1 and
        "initial_group_size". Only used with "start_short_after", and
        defaults to "quorum". "quorum" defaults to it and may not
        exceed it, so that a group started this way is not below
        quorum at its first barrier.

      * **max_wait_time** -- How long a participant may wait for a
        group (default 20 seconds), and what happens then: ""fail""
        (default) fails them, and ""continue_without_group"" lets them
        carry on without a group (see "Grouper").

      * **max_wait_action** -- How long a participant may wait for a
        group (default 20 seconds), and what happens then: ""fail""
        (default) fails them, and ""continue_without_group"" lets them
        carry on without a group (see "Grouper").

      * **kwargs** -- Further arguments to pass to Grouper, such as
        "waiting_message".

   choose_who_to_release(waiting_participants)

      Release waiters who can join an open group, then group the rest.

      Participants who arrive while a group is open join it before
      reaching the barrier. Those already waiting, such as leftovers
      from a burst of arrivals that was not a multiple of
      "initial_group_size", join here once a group opens.

   expected_release_time(participant)

      Return when the waiting participants will start short, in epoch
      seconds.

      "None" until "start_short_with" participants are waiting, or
      without "start_short_after".

      Return type:
         "Optional"["float"]

   group(participants)

      This method is run if "ready_to_group" returns "True". It is
      responsible for grouping participants.

      Parameters:
         **participants** ("List"["Participant"]) -- Participants who
         are candidates for grouping.

      Return type:
         A list of SyncGroups who should be populated by the grouped
         participants.

   property min_group_size

      Deprecated name for "quorum".

   ready_to_group(participants)

      Determines whether the Grouper is ready to group a given
      collection of participants. Note that not all participants need
      to be grouped at once; it's permissible to leave some
      participants still waiting.

      Parameters:
         **participants** ("List"["Participant"]) -- List of
         participants who are candidates for grouping.

      Return type:
         "bool"

      Returns:
         * "True" if the grouper is ready to group (some of) the
           participants, "False" otherwise.

   would_release(waiting_participants)

      Return whether a check would form a group or let a waiter join
      one.

      Return type:
         "bool"

class psynet.sync.SimpleSyncGroup(*args, **kwargs)

   Bases: "SyncGroup"

   A SyncGroup that is created by a SimpleGrouper.

   accepts_top_ups

      Whether newcomers may join; only "SimpleSyncGroup" takes top-
      ups.

   below_quorum

      ""fail"" or ""continue_without_group"".

      Type:
         What happens to members when the group dissolves below quorum

   below_quorum_since

      When the group last fell below its quorum while accepting
      newcomers.

   creation_time

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   dissolve_if_below_quorum()

      Dissolve a group without top-ups that fell below its quorum.

      If a member is busy in another request, the barrier poller
      dissolves the group shortly after instead; see
      "SyncGroup._dissolve()".

   failed

      boolean indicating whether the Network has failed which prompts
      Dallinger to ignore it unless specified otherwise. Objects are
      usually failed to indicate something has gone wrong.

   failed_reason

      an optional reason the object was failed. If the object is
      failed as part of a cascading failure triggered from another
      object, the chain of objects will be captured in this field.

   id

      a unique number for every entry. 1, 2, 3 and so on...

   property1

      a generic column that can be used to store experiment-specific
      details in String form.

   property2

      a generic column that can be used to store experiment-specific
      details in String form.

   property3

      a generic column that can be used to store experiment-specific
      details in String form.

   property4

      a generic column that can be used to store experiment-specific
      details in String form.

   property5

      a generic column that can be used to store experiment-specific
      details in String form.

   quorum

      How many active members the group needs to keep going.

   remove_participant(participant, reason)

      Remove a participant from the group.

      Parameters:
         * **participant** ("Participant") -- The member to remove.

         * **reason** ("Literal"["'removed_by_experimenter'",
           "'left_experiment'", "'late'", "'waited_too_long'",
           "'group_dissolved'", "'moved_on'", "'finished'",
           "'not_admitted'"]) --

           Why they left, stored on their link and returned by
           "sync_group_removal_reason()". A "GroupPrompt" that still
           draws them for their answer labels them "(left)" unless the
           reason is ""moved_on"" or ""finished"" (see Showing the
           group).

           * ""removed_by_experimenter"": removed without a more
             specific reason, for example from the dashboard.

           * ""left_experiment"", ""waited_too_long"" or
             ""group_dissolved"": they dropped out.

           * ""late"": a barrier removed them for being late (with any
             "late_action").

           * ""moved_on"": for a member who left at a "Regrouper", for
             their next group or to sit the round out. A pair a
             "SimpleGrouper" formed isn't dissolved, failing the
             partner, when the first member reaches a "Regrouper".

           * ""finished"": for a member who has played their part,
             such as a player leaving a cohort after their last round.
             The members finishing their own last rounds aren't told
             that too few remained.

           PsyNet itself records ""not_admitted"" for a pending member
           it turns away (see "pending_participants").

           Leaving with ""finished"" or ""moved_on"" doesn't dissolve
           the group by itself; other reasons can. Either way, the
           group's next "GroupBarrier" can dissolve a group left below
           its quorum. See Groups below quorum for the full rule.

   stop_top_ups()

      Stop newcomers joining this group, so that it no longer waits
      for them.

      For a group formed with "join_existing_groups=True", for example
      once the game has started, so nobody joins it under way. From
      then on it is treated as a group without top-ups (see Groups
      below quorum); its pending members are turned away as
      ""not_admitted"", and a group already below its quorum is
      dissolved, usually at once. Groups below quorum lists the other
      ways top-ups stop.

   target_group_size

      How many members an admission point waits for, up to
      "top_up_wait"; see "SimpleGrouper(target_group_size=...)".

   time_of_death

      the time at which failing occurred

   top_up_wait

      Seconds a group below quorum waits for newcomers; see
      "SimpleGrouper(top_up_wait=...)".

   top_ups_stopped_at

      When the group stopped accepting top-ups, or "None" while it
      accepts them or if it never did.

   type

   uses_admission_points

      Whether newcomers wait as pending members for an admission point
      instead of joining at once; see
      "SimpleGrouper(use_admission_points=...)".

   vars

class psynet.sync.SyncGroup(*args, **kwargs)

   Bases: "Base", "SQLMixin"

   A SyncGroup represents a group of participants that are
   synchronized at various points in the experiment. Such groups are
   created by Groupers and synchronized by GroupBarriers.

   leader

      The leader of the SyncGroup. This can be reassigned by logic
      such as "group.leader = participant".

      Type:
         Participant

   accepts_top_ups = False

      Whether newcomers may join; only "SimpleSyncGroup" takes top-
      ups.

   property active_participants: List[Participant]

      The admitted members who are still working, in the order they
      joined.

      Barriers wait for them, the quorum counts them, the leader is
      one of them, and "GroupPrompt" draws them. Pending members (see
      "pending_participants") are not included.

   add_participant(participant)

      Add a participant to the group as an admitted member (creates an
      active link).

      If an active member already has the newcomer's derived pseudonym
      and this is the newcomer's first group, the newcomer is given a
      free one, so members can tell each other apart. Pseudonyms set
      with "set_pseudonym()" are kept, and later groups never rename
      anyone, so a pseudonym stays the same once others have seen it.

   check_leader()

      Make the lowest-id active member leader if the leader has left.

   close()

      End the group, turning away its pending members as
      ""not_admitted"".

   creation_time

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   dissolve_if_below_quorum()

      Dissolve the group if it fell below its quorum; groups without a
      quorum never do.

   failed

      boolean indicating whether the Network has failed which prompts
      Dallinger to ignore it unless specified otherwise. Objects are
      usually failed to indicate something has gone wrong.

   failed_reason

      an optional reason the object was failed. If the object is
      failed as part of a cascading failure triggered from another
      object, the chain of objects will be captured in this field.

   id

      a unique number for every entry. 1, 2, 3 and so on...

   property participants: List[Participant]

      Read-only list of participants currently in the group (links
      with "active=True").

      Includes pending members (see "pending_participants"); use
      "active_participants" for the admitted ones still working. Use
      "group.add_participant(participant)" to add a participant.

   property pending_participants: List[Participant]

      Members who have joined but not been admitted yet, in the order
      they joined.

      Only a grouper with "use_admission_points=True" makes pending
      members: each holds a seat until the group's next admission
      point admits them or turns them away (see Admission points).

   property1

      a generic column that can be used to store experiment-specific
      details in String form.

   property2

      a generic column that can be used to store experiment-specific
      details in String form.

   property3

      a generic column that can be used to store experiment-specific
      details in String form.

   property4

      a generic column that can be used to store experiment-specific
      details in String form.

   property5

      a generic column that can be used to store experiment-specific
      details in String form.

   quorum = None

      Quorum and below-quorum policy; only "SimpleSyncGroup" sets
      them.

   remove_participant(participant, reason)

      Remove a participant from the group.

      Parameters:
         * **participant** ("Participant") -- The member to remove.

         * **reason** ("Literal"["'removed_by_experimenter'",
           "'left_experiment'", "'late'", "'waited_too_long'",
           "'group_dissolved'", "'moved_on'", "'finished'",
           "'not_admitted'"]) --

           Why they left, stored on their link and returned by
           "sync_group_removal_reason()". A "GroupPrompt" that still
           draws them for their answer labels them "(left)" unless the
           reason is ""moved_on"" or ""finished"" (see Showing the
           group).

           * ""removed_by_experimenter"": removed without a more
             specific reason, for example from the dashboard.

           * ""left_experiment"", ""waited_too_long"" or
             ""group_dissolved"": they dropped out.

           * ""late"": a barrier removed them for being late (with any
             "late_action").

           * ""moved_on"": for a member who left at a "Regrouper", for
             their next group or to sit the round out. A pair a
             "SimpleGrouper" formed isn't dissolved, failing the
             partner, when the first member reaches a "Regrouper".

           * ""finished"": for a member who has played their part,
             such as a player leaving a cohort after their last round.
             The members finishing their own last rounds aren't told
             that too few remained.

           PsyNet itself records ""not_admitted"" for a pending member
           it turns away (see "pending_participants").

           Leaving with ""finished"" or ""moved_on"" doesn't dissolve
           the group by itself; other reasons can. Either way, the
           group's next "GroupBarrier" can dissolve a group left below
           its quorum. See Groups below quorum for the full rule.

   rounds(module_id)

      Return the group's rounds in a module, in round order.

      Each round is a "SyncGroupRound", whose "var" holds what the
      round stored and "trials" its trials. It also works once the
      group has ended or dissolved, for example to show a debrief
      after the game:

         sentences = [r.var.get("sentence") for r in group.rounds("story")]

      Parameters:
         **module_id** ("str") -- The "id_" of the module whose rounds
         to return, as in "participant.module_id".

      Returns:
         Ordered by "number", then by creation; empty if the group has
         played no round in the module.

      Return type:
         list of SyncGroupRound

   stop_top_ups()

      Stop newcomers joining this group; a no-op for groups that never
      take them.

   time_of_death

      the time at which failing occurred

   top_ups_stopped_at = None

      When the group stopped accepting top-ups; see "SimpleSyncGroup".

   type

   uses_admission_points = False

      When newcomers are admitted and how many an admission point
      waits for; only "SimpleSyncGroup" takes newcomers.

   vars

psynet.sync.SyncGroupOutcome

   Values of "sync_group_outcome" other than "None": ""stayed"" once a
   barrier in the trial's pages releases the group with the player in
   it, after which it doesn't change; before that, the "RemovalReason"
   they left with.

   alias of "Literal"['stayed', 'removed_by_experimenter',
   'left_experiment', 'late', 'waited_too_long', 'group_dissolved',
   'moved_on', 'finished', 'not_admitted']

class psynet.sync.SyncGroupRound(*args, **kwargs)

   Bases: "Base", "SQLMixin"

   One round that a sync group plays together, linking the members'
   trials in it.

   A round is made either by "cue()" for a trial class with
   "sync_group_type" ("trial_maker_id" is "None"), when the round's
   first member cues it, or by a trial maker with "sync_group_type"
   each time it prepares the group's trials. See Rounds of cued trials
   and rounds of a trial maker for when rounds open and close.

   sync_group_id

      The "SyncGroup" playing the round.

      Type:
         int

   module_id

      The module the round was played in; for a trial maker, its "id".

      Type:
         str

   trial_maker_id

      The trial maker that made the round, or "None" for cued rounds.

      Type:
         str or None

   number

      The round's number, counted from 0 for each group, separately in
      each module of cued trials and in each trial maker. It equals
      "sync_group_round" on the round's trials.

      Type:
         int

   definition

      For cued rounds, the definition shared by every trial in the
      round, set by its first cue. "None" for trial makers' rounds,
      whose trials keep their own definitions.

      Type:
         dict

   var

      A variable store for the group's results in the round, for
      example those that a "GroupBarrier"'s "on_release" computes.

   closed_at

      When the round closed: when a "GroupBarrier" in the round's
      trials released the group, or, for a trial maker's round that
      has no such barrier, when the group's next trials were prepared.
      A closed cued round takes no members who have no trial in it.

      Type:
         datetime or None

   dissolved_at

      When the group dissolved during the round, or "None" if it
      didn't. Set when the group dissolves (see Groups below quorum)
      while a member still in the group is in their trial in this
      round (the trial's "complete" is "False") and the round is not
      closed. So a round the group finished stays "None" even if a
      member is still on a page after the barrier, and so does a round
      whose remaining members' trials had all ended before the group
      dissolved. Written under the members' row locks, so it is never
      set on a closed round.

      Type:
         datetime or None

   trials

      The members' trials in the round, including failed ones.

      Type:
         list of Trial

   creation_time

      the time at which the Network was created.

   details = None

      a generic column for storing structured JSON data

   failed

      boolean indicating whether the Network has failed which prompts
      Dallinger to ignore it unless specified otherwise. Objects are
      usually failed to indicate something has gone wrong.

   failed_reason

      an optional reason the object was failed. If the object is
      failed as part of a cascading failure triggered from another
      object, the chain of objects will be captured in this field.

   id

      a unique number for every entry. 1, 2, 3 and so on...

   property1 = None

      a generic column that can be used to store experiment-specific
      details in String form.

   property2 = None

      a generic column that can be used to store experiment-specific
      details in String form.

   property3 = None

      a generic column that can be used to store experiment-specific
      details in String form.

   property4 = None

      a generic column that can be used to store experiment-specific
      details in String form.

   property5 = None

      a generic column that can be used to store experiment-specific
      details in String form.

   property sync_group: SyncGroup | None

      The "SyncGroup" playing the round.

   time_of_death

      the time at which failing occurred

   type

   vars

psynet.sync.arrival_notice_payload(unique_id)

   Return the partner-ready notice and ready seats for one
   participant.

   Redis arrival wakes are fire-and-forget. The browser fetches this
   when the arrival websocket opens so a partner who arrived during
   connect is still shown.

psynet.sync.check_admission_points(barriers)

   Check the admission points of groups that admit newcomers at them.

   Each "SimpleGrouper" with "use_admission_points=True" needs an
   admission point for its group type: a
   "GroupBarrier(admission_point=True)", a synchronized trial maker's
   trial preparation, or a "Regrouper" with "within" that type.
   Without one its newcomers would never be admitted, so this warns.

   Parameters:
      **barriers** (*iterable** of **Barrier*) -- The barriers in the
      timeline.

   Raises:
      **ValueError** -- If an admission point of such a group type
      lacks "newcomer_max_wait"     ("sync_group_newcomer_max_wait"
      for a trial maker).

psynet.sync.check_barriers()

   Process waiting barrier visits, including stacked holds created
   here.

   Last-arrival GET waits for this poller's extra-connection instance
   claim. The poller keeps that claim until its own skip-after-commit
   finishes. It skips waiters **this poller** released; last-arrival
   does not skip partner cursors. Walk newly created holds in this
   sweep and keep wake publishes unpublished until that walk returns.
   Each visit still commits before the next check so a locked waiter
   cannot poison sibling checks.

   Each sweep first retries group dissolutions that waited for a busy
   member and times out overdue waiters, then checks visits: first
   those whose "next_due_at" has come (each due time once), then the
   least recently checked, with new or changed ones given a head
   start. Each of the two steps stops starting new work after
   "_POLLER_SWEEP_BUDGET_SECONDS", so thousands of idle waiters cannot
   keep the poller busy; the rest wait for later sweeps. One item can
   still overrun the budget while it waits for a row lock. A waiter's
   page reload ("GET /timeline") or a bot's poll also checks their own
   visit; a browser's hold poll does not. A sweep that found waiting
   visits ends by reporting groups whose members wait at different
   barriers (see "_report_divergences()").

psynet.sync.check_group_dropout_policies(barriers)

   Check that groups which late members can shrink say what happens to
   the rest.

   A "GroupBarrier" with "late_after" removes late members from its
   group, and from the groups in "also_leave", so each "SimpleGrouper"
   forming such a group must be given "below_quorum". With
   "late_action="leave_group"" it must not be ""fail"", which would
   fail the members who were on time while the late one carries on.

   A barrier with "late_after" has no "max_wait_time", so a group that
   falls below its quorum there while it waits for newcomers would
   wait forever once they stop coming. Groupers whose groups may wait
   for newcomers at such a barrier, before a "stop_top_ups=True"
   barrier stops their top-ups, must therefore set "top_up_wait".

   Parameters:
      **barriers** (*iterable** of **Barrier*) -- The barriers in the
      timeline, in timeline order. Barriers built inside a trial's
      "show_trial" are checked by "check_late_removal_policies()" when
      the trial is shown; those built in a "for_loop" or another
      "PageMaker" are not visible, and
      "GroupBarrier._dissolve_after_late_removal()" warns about them
      at runtime.

   Raises:
      **ValueError** -- If a grouper lacks "below_quorum", combines
      "below_quorum="fail""     with a barrier's
      "late_action="leave_group"", or lacks a     "top_up_wait" that
      such a barrier needs.

psynet.sync.check_late_removal_policies(barriers, participant)

   Check barriers built at runtime against the stored groups they
   remove late members from.

   "check_group_dropout_policies()" only sees the timeline's top-level
   barriers, so "psynet.trial.main.Trial._show_trial()" calls this for
   the barriers in "show_trial", using the "below_quorum" stored on
   "participant"'s groups.

   Parameters:
      * **barriers** (*iterable** of **Barrier*) -- The barriers to
        check.

      * **participant** (*Participant*) -- The participant whose
        active groups the barriers act on.

   Raises:
      **ValueError** -- If a barrier with "late_action="leave_group""
      acts on a group with     "below_quorum="fail"", or a
      "late_after" barrier acts on a group     that could wait there
      for newcomers without a "top_up_wait".

psynet.sync.check_sync_groups()

   Recount active membership and close groups with no active members
   left.

   Members who finish or return the experiment stay linked to their
   groups, so this is what closes a group once all of them are gone.
   It closes any active "SyncGroup" with no admitted or pending
   members, including emptied groups that accept top-ups, unless the
   group is still dissolving. Groups locked by another request are
   skipped until the next tick.

   One query first counts every active group's members (see
   "_groups_to_recount()"), so only groups whose stored counts are
   stale, or that may close, are locked and recounted.

   Dedicated sessions keep these maintenance commits separate from any
   transaction owned by the caller. Each group's recount runs in its
   own transaction so a failure cannot roll back sibling groups
   already processed.

psynet.sync.fail_on_group_divergence()

   Raise "GroupDivergenceError" after the block if "check_barriers()"
   recorded one during it.

   Bot tests run inside it, so a divergence fails "psynet test local"
   with its message even though the poller found it in another
   process. Records from before the block, such as an earlier run
   against the same server, are ignored. The error is raised even if
   the block raised, as bots stuck at diverged barriers fail on
   "max_wait_time".

psynet.sync.group_seats(group)

   Return "{participant_id: seat}" for everyone who has been admitted
   to "group".

   Seats number members in the order they were first admitted. Links
   are kept when members leave, so seats never change while the group
   exists, and pages can refer to members without their IDs. Pending
   members get a seat once admitted, and members turned away never get
   one.

   Return type:
      "Dict"["int", "int"]

psynet.sync.hold_message(title, progress=None)

   Return a waiting message with its own progress line.

   By default, a "GroupBarrier"'s waiting indicator shows its
   "waiting_message" with a smaller progress line underneath in groups
   of three or more ("1 of 3 not ready yet"). Return
   "hold_message(title, progress)" from a "waiting_message" function
   to write that line yourself, or leave out "progress" to show no
   progress line. The message is redrawn as members arrive unless the
   barrier has "on_arrival_message=None".

   Parameters:
      * **title** -- The waiting message, as for "waiting_message".

      * **progress** -- Optional second line, for example
        "f"{waiting_count} of {group_size} are ready"".

   -[ Examples ]-

      def waiting_text(waiting_count, group_size):
          return hold_message(
              "Waiting for the rest of the room…",
              f"{waiting_count} of {group_size} have chosen",
          )

      GroupBarrier(id_="chosen", group_type="room", waiting_message=waiting_text)

psynet.sync.leave_group(group_type, reason='finished')

   Return a timeline step that takes the participant out of their
   "group_type" group.

   For example, put "leave_group("cohort")" after a player's last
   round, so that cohort members who are still playing, and any
   "Regrouper" pairing them, don't wait for them. The step does
   nothing if the participant is in no group of that type.

   Parameters:
      * **group_type** ("str") -- The type of the group to leave.

      * **reason** ("Literal"["'removed_by_experimenter'",
        "'left_experiment'", "'late'", "'waited_too_long'",
        "'group_dissolved'", "'moved_on'", "'finished'",
        "'not_admitted'"]) -- Passed to
        "SyncGroup.remove_participant()". Leaving with the default,
        ""finished"", doesn't dissolve the group by itself, even if it
        leaves the group below its quorum; but the group's next
        "GroupBarrier" can still dissolve it then, unless it is
        waiting for newcomers (see Groups below quorum).

   Return type:
      CodeBlock

psynet.sync.pending_arrival_notice_for(participant)

   Return a partner-ready notice if this participant is behind a
   waiter.

   Reconstructs registry barriers for this call only. Overlay HTML
   stays on the live timeline barrier. Unreconstructable specs are
   skipped.

psynet.sync.reached_barrier_after_time_limit(participant, group)

   Return whether "participant" reached the barrier of "group" they
   wait at because a time limit ran out.

   That is, they are waiting at a barrier of "group" that they reached
   after the time limit of their latest timed page ran out; untimed
   pages in between, and a trial's feedback pages even if timed, don't
   count.

   Return type:
      "bool"

psynet.sync.released_waiting_barrier(page, participant)

   Return the barrier if this is its interruptible waiting page and it
   released the participant.

   The waiting-status route uses the same test, so the browser only
   ends a waiting page when the server will accept the interrupt.

psynet.sync.waiting_page_config(page, participant)

   Return the browser config for a page shown while waiting at a
   barrier, or "None".

   Every page shown during "waiting_logic" checks in, including pages
   that trial makers generate there, so each can count down to the
   release. "release_grace_ms" is "None" unless a release may end the
   page. The participant may already have been released while this
   page was being built; the page's first status check then ends it.
   Timeline holds get no config, because they already poll for their
   release.

psynet.sync.waiting_status_payload(unique_id, barrier_id)

   Return whether a participant on a waiting page has been released.

   Waiting pages fetch this about every 2 seconds. "ends_page" tells
   whether the participant's current page would now accept an
   interrupt (see "released_waiting_barrier()"); a released
   participant whose page may not be ended, for example with
   "release_grace=None", gets "released" without "ends_page" and
   finishes the page normally. "release_in_ms" is the time left until
   "Barrier.expected_release_time()", or "None".

Declarative persistence for barrier release behavior.

Barrier instances must survive across web workers, but persisting an
entire "Barrier" object also captures waiting pages and incidental ORM
state. This module stores the importable barrier class, release-hook
state, scalar presentation ("waiting_message", timeouts), and arrival-
notice settings. Waiting pages and hold-page construction
("waiting_logic", "waiting_screen", "_uses_timeline_hold" and the
expected repetitions of "waiting_logic") stay on the live timeline
object. See "Barrier" for which methods are live-only. Callback
identity is kept separate from the ORM receiver selected for one
visit, so behavior comparisons are stable while invocation remains
correctly bound.

exception psynet.barrier_spec.BarrierSpecError

   Raised when barrier behavior cannot be represented declaratively.

psynet.barrier_spec.barrier_from_spec_json(serialized)

   Reconstruct a registry barrier from canonical JSON.

   The result is a callback/release object: scalar presentation and
   notifications are restored. Waiting pages and hold-page
   construction stay on the live timeline barrier. See "Barrier" for
   which methods are live-only.

psynet.barrier_spec.barrier_spec(barrier)

   Return a JSON-compatible specification of a barrier's release
   behavior.

psynet.barrier_spec.barrier_spec_json(barrier)

   Serialize release behavior to canonical JSON.

psynet.barrier_spec.behavior_hash(barrier)

   Return a stable hash of release behavior, excluding callback
   receivers.

psynet.barrier_spec.behavior_hash_from_json(serialized)

   Hash a serialized spec after removing visit-local callback
   bindings.
