Recruiters
**********

PsyNet recruiter integrations.

This module wraps Dallinger's recruiter classes (Prolific and
generic/CLI) and implements PsyNet-specific recruiters (Lucid and
LabRecruiter). Recruiters own the participant lifecycle at the
platform boundary: opening and closing recruitment, routing
participants back to the platform at the end of the experiment, and
paying base payments and bonuses.

Key design constraints for maintainers:

* Recruiter classes are typically composed as
  "PsyNet<X>RecruiterMixin" plus the corresponding Dallinger
  recruiter, so PsyNet behavior layers on top of Dallinger's via the
  MRO. Mixin overrides should call "super()" where the Dallinger
  implementation is still wanted.

* End-of-experiment payment flows differ per platform. For Prolific,
  local submit is the success path: PsyNet completes the submission
  server-side ("COMPLETE" with a researcher-actor code), Prolific pays
  "base_payment" or the fixed screen-out reward, and PsyNet tops up
  with a bonus. Unsuccessful (failed/errored) participants use the
  "UNSUCCESSFUL" screen-out code when "prolific_pay_unsuccessful" is
  enabled (the default; see
  "PsyNetProlificRecruiterMixin.completion_codes_and_actions"), or are
  asked to return their submission for a bonus (the legacy fallback
  when "prolific_pay_unsuccessful = false").

* Payment is split into decide / record / transfer. "decide_payment"
  returns a "PaymentDecision" (status, platform base, bonus) from the
  participant's outcome and recruiter policy; "record_payment" writes
  those fields onto the participant; "report_submission_outcome"
  reports the terminal outcome and delegates real bonus transfers to
  "reward_bonus" by default. Recruiters with "reports_zero_outcomes"
  (Lab Recruiter, Lucid) also report zero bonuses through that hook,
  and implement the outcome there. Calling "reward_bonus" on those
  recruiters raises. "False" means the platform rejected the report or
  transfer. "Experiment.on_recruiter_submission_complete" owns this
  sequence, always re-recording status and platform base, and uses
  "bonus_status" to skip a repeat transfer. PsyNet posts a bonus
  automatically at most once per participant. A failed transfer still
  continues recruitment, stores the amount on "planned_bonus", sets
  "bonus_status" to unconfirmed, and records "bonus_attempt_detail"
  from the last pay attempt. The Participants dashboard lists everyone
  who needs that review. Opening a participant polls the platform
  (Prolific "bonus_payments" and submission status, which may lag a
  POST) and shows those facts in the participant table, with Pay bonus
  or Dismiss when review is needed. "reward_bonus" returns "False" if
  the platform rejected the transfer. PsyNet does not call Dallinger's
  unused "data_check" / "attention_check" hooks.

* After Submit, Prolific participants go to a PsyNet confirmation page
  (timeline after error Submit, recruiter-exit after Finish). They are
  not redirected to enter a completion code.

psynet.recruiters.BaseCapRecruiter

   alias of "BaseLabRecruiter"

class psynet.recruiters.BaseLabRecruiter(*args, **kwargs)

   Bases: "PsyNetRecruiterMixin", "PsyNetExitPageMixin",
   "CLIRecruiter"

   The LabRecruiter base class.

   The external submission URL (where completion/failure outcomes are
   posted) can be overridden via the experiment config key
   "lab_recruiter_external_submission_url". Completion posts
   authenticate with "lab_recruiter_auth_token", normally set in
   "~/.dallingerconfig". Non-debug launches require it. Deployment
   copies the resolved config into the container environment, so the
   token reaches the deployed app under that same key.

   after_rejected_consent(experiment, participant)

      Post fail when the participant rejects consent and never reaches
      submission.

   close_recruitment()

      Talk about closing recruitment.

   get_status()

      Return the status of the recruiter as a RecruitmentStatus.

      Return type:
         "LabRecruitmentStatus"

   notify_duration_exceeded(participants, reference_time)

      The participant has been working longer than the time defined in
      the "duration" config value.

   open_recruitment(n=1)

      Return an empty list which otherwise would be a list of
      recruitment URLs.

   recruit(n=1)

      Incremental recruitment isn't implemented for now, so we return
      an empty list.

   report_submission_outcome(participant, amount, reason)

      Report a terminal Lab Recruiter outcome, including a zero bonus.

   reward_bonus(participant, amount, reason)

      Lab Recruiter does not transfer bonuses through "reward_bonus".

   validate_config(**kwargs)

      Require a Lab Recruiter auth token for non-debug launches.

class psynet.recruiters.BaseLucidRecruiter(*args, **kwargs)

   Bases: "PsyNetRecruiterMixin", "CLIRecruiter"

   check_consents(consents)

      Check that the consent elements are suitable for the recruiter.
      By default this check is skipped in "psynet debug local".

      Parameters:
         **consents** (*list*) -- List of consent objects from the
         timeline

   close_recruitment()

      Stop new entrants, and complete the survey once nobody is still
      working.

      PsyNet calls this as soon as finished plus working participants
      cover the target. Lucid records anyone who returns after the
      survey leaves "live" as Survey Closed (code 136) rather than as
      a complete, so while participants are still working the survey
      stays "live" and entry is paused by lowering its total quota to
      the completes Lucid already has. "run_checks" re-evaluates
      recruitment every minute while entry is paused, which completes
      the survey once the last working participant has finished or
      timed out, or reopens entry if more are needed.

   current_survey_number()

      Return the survey number associated with the active experiment
      ID if any such survey exists.

   current_survey_sid()

      Return the survey SID associated with the active experiment ID
      if any such survey exists.

   decide_payment(participant, *, experiment)

      Keep terminated Lucid sessions at returned with no PsyNet
      payment.

      Return type:
         "PaymentDecision"

   early_exit_allowed(participant)

      Allow Lucid termination regardless of PsyNet's reward threshold.

      Return type:
         "bool"

   error_page_presentation(*, participant=None, plan=None, assignment_id=None, external_submit_url=None, contact_address=None)

      Explain Lucid's return to the participant's panel provider.

      Return type:
         "ErrorRecoveryPresentation"

   execute_early_exit_plan(experiment, participant, plan)

      Terminate the panel session described by a Lucid exit plan.

      Voluntary Leave terminates via the Lucid API within the route's
      transaction. Error recovery preserves Lucid's established
      behavior: the error route records termination details and the
      browser follows the generated terminate URL, without a second
      API termination.

      Return type:
         "None"

   exit_response(experiment, participant)

      Delegate to the experiment for possible values to show to the
      participant and complete the survey.

   get_participant(assignment_id)

      Return the participant with this Lucid RID, or "None".

      Parameters:
         **assignment_id** (*str*) -- The Lucid RID, as returned by
         "requested_assignment_id()".

      Returns:
         The participant, or "None" if no participant has this RID.

      Return type:
         Participant or None

      Raises:
         **MultipleResultsFound** -- If several participants have this
         RID.

   get_status(submissions=None)

      Return the status of the recruiter as a RecruitmentStatus.

      Return type:
         "LucidRecruitmentStatus"

   property in_progress

      Does a Lucid survey for the current experiment ID already exist?

   link_lucid_rid_to_participant(participant)

      Link the LucidRID row for this participant's RID when present.

   market_place_codes = {-6: 'Sent to Marketplace Intermediate', -5: 'Sent to External Intermediate', -1: 'Error', 1: 'In Screener', 3: 'In Client Survey', 21: 'Industry Lockout', 23: 'Standard Qualification', 24: 'Custom Qualification', 30: 'Quality Term: Unique IP', 31: 'Quality Term: RelevantID Duplicate', 32: 'Quality Term: Invalid Traffic', 35: 'Quality Term: Supplier PID Duplicate', 36: 'Quality Term: Cookie Duplicate', 37: 'Quality Term: GEO IP Mismatch', 38: 'Quality Term: RelevantID** Fraud Profile', 40: 'Overquota: Quota Full', 41: 'Overquota: Supplier Allocation', 42: 'Overquota: Survey Closed for Entry', 50: "Financial Term: CPI Below Supplier's Rate Card", 98: 'Exit: End of Router', 120: 'Pre-Client Survey Opt Out', 122: 'Return to Marketplace Opt Out', 123: 'Max Client Survey Entries', 124: 'Max Time in Router', 125: 'Max Time in Router Warning Opt Out', 126: 'Max Answer Limit', 131: 'Quality Term: Supplier Encryption Failure', 132: 'Quality Term: Blocked PID', 133: 'Quality Term: Blocked IP', 134: 'Quality Term: Max Completes per Day Terminate', 138: 'Quality Term: Survey Group Cookie Duplicate', 139: 'Quality Term: Survey Group Supplier PID Duplicate', 230: 'Quality Term: Survey Group Unique IP', 234: 'OFAC Term: Blocked Country IP', 236: 'Privacy Term: No Privacy Consent', 237: 'Privacy Term: Minimum Age', 238: 'Quality Term: Found on Deny List', 240: 'Quality Term: Invalid Browser', 241: 'Quality Term: Respondent Threshold Limit', 242: 'Quality Term: Respondent Quality Score', 243: 'Quality Term: Marketplace Signature Check'}

      The LucidRecruiter base class

   normalize_entry_information(entry_information)

      Accepts data from the recruited user and returns data needed to
      validate, create or load a Dallinger Participant.

      See "create_participant()" for details.

      The default implementation extracts "hit_id", "assignment_id",
      and "worker_id" values directly from "entry_information".

      This implementation extracts the "RID" from "entry_information"
      and assigns the value to "hit_id", "assignment_id", and
      "worker_id".

   notify_duration_exceeded(participants, reference_time)

      The participant has been working longer than the time defined in
      the "duration" config value.

   open_recruitment(n=1)

      Open a connection to Lucid and create a survey.

   plan_exit(experiment, participant, context)

      Plan completion or termination of a Lucid panel session.

      Return type:
         "ExitPlan"

   prepare_error_recovery(participant)

      Record Lucid termination details before the browser handoff.

      Return type:
         "None"

   record_error_termination(assignment_id, reason='error-page_route')

      Record Lucid's error-page termination details for an assignment.

   recruit(n=1)

      Reopen entry if "close_recruitment" paused it; Lucid sends the
      entrants.

   release_participant(experiment, participant)

      Return terminated sessions directly to Lucid without submission.

      Return type:
         "Union"["Elt", "List"["Elt"], "EltCollection"]

   report_submission_outcome(participant, amount, reason)

      Complete or terminate the respondent on Lucid, even with a zero
      bonus.

      Returns False if the Lucid complete or terminate call raises.

   static requested_assignment_id(request)

      Return the Lucid RID that a request names.

      The RID may come from "assignmentId", "RID" or the part of
      "unique_id" after the colon. Not from "participant_id": it is
      sequential, and the page this request renders shows the
      participant's RID.

      Parameters:
         **request** (*flask.Request*) -- The incoming request.

      Returns:
         The RID.

      Return type:
         str

      Raises:
         * **ValueError** -- If the request names no RID or
           "unique_id" is malformed.

         * **LucidIdentifierMismatch** -- If the supplied identifiers
           name different RIDs.

   required_consent_page

      alias of "LucidConsentPage"

   reward_bonus(participant, amount, reason)

      Lucid does not transfer bonuses through "reward_bonus".

   shows_error_recovery_page(plan)

      Lucid recovery explains the panel return before redirecting.

      Return type:
         "bool"

   shows_reward_by_default = False

      Whether participants are shown their accumulated reward when the
      experiment does not say either way. Recruiters that disburse
      money through a platform show it; local and generic recruitment
      does not, because in those cases PsyNet cannot pay anyone and
      quoting a figure promises something the experimenter has to
      honour by hand.

   terminate_participant(participant=None, assignment_id=None, reason=None, details=None, *, raise_on_error=False)

      Terminate a Lucid participant and return their terminate URL.

      "LucidService.terminate_respondent()" commits as soon as Lucid
      confirms, so this always raises inside timeline steps; call it
      from an "AsyncCodeBlock" there. Lucid API failures are logged
      rather than raised unless "raise_on_error" is set, because most
      callers are timeout handlers that must still send the
      participant back to the panel.

psynet.recruiters.CapRecruiter

   alias of "LabRecruiter"

psynet.recruiters.CapRecruitmentStatus

   alias of "LabRecruitmentStatus"

psynet.recruiters.DevCapRecruiter

   alias of "DevLabRecruiter"

class psynet.recruiters.DevLabRecruiter(*args, **kwargs)

   Bases: "DevRecruiter", "BaseLabRecruiter"

   The development lab-recruiter.

   Used by "psynet debug local" when "debug_recruiter = dev-lab-
   recruiter". Posts completion/failure to
   "http://localhost:8000/tasks" unless
   "lab_recruiter_external_submission_url" overrides it.

class psynet.recruiters.DevLucidRecruiter(*args, **kwargs)

   Bases: "DevRecruiter", "BaseLucidRecruiter"

   Development recruiter for the Lucid Marketplace.

   get_status(submissions=None)

      Return the status of the recruiter as a RecruitmentStatus.

      Return type:
         "LucidRecruitmentStatus"

class psynet.recruiters.DevProlificRecruiter(*args, **kwargs)

   Bases: "PsyNetProlificRecruiterMixin", "DevProlificRecruiter"

   open_recruitment(n=1)

      Open a simulated Prolific study, saying that nothing was
      created.

      Return type:
         "dict"

class psynet.recruiters.GenericRecruiter

   Bases: "PsyNetRecruiterMixin", "PsyNetExitPageMixin",
   "CLIRecruiter"

   An improved version of Dallinger's Hot-Air Recruiter.

   exit_response(experiment, participant)

      Delegate to the experiment for possible values to show to the
      participant.

   has_external_bonus_payment()

      Generic/local recruitment does not pay through an external
      platform.

      Return type:
         "bool"

   notify_duration_exceeded(participants, reference_time)

      The participant has been working longer than the time defined in
      the "duration" config value.

   open_recruitment(n=1)

      Return initial experiment URL list, plus instructions for
      finding subsequent recruitment events in experiment logs.

   recruit(n=1)

      Generate experiment URLs and print them to the console.

   shows_reward_by_default = False

      Whether participants are shown their accumulated reward when the
      experiment does not say either way. Recruiters that disburse
      money through a platform show it; local and generic recruitment
      does not, because in those cases PsyNet cannot pay anyone and
      quoting a figure promises something the experimenter has to
      honour by hand.

   supports_max_concurrent_participants = True

      Whether "max_concurrent_participants" may hold newcomers on the
      start page. Only open-link recruiters support it; see
      "psynet.capacity".

class psynet.recruiters.HotAirRecruiter

   Bases: "PsyNetRecruiterMixin", "PsyNetExitPageMixin",
   "HotAirRecruiter"

   get_status()

      Return the status of the recruiter as a RecruitmentStatus.

      Return type:
         "RecruitmentStatus"

   has_external_bonus_payment()

      HotAir does not pay through an external recruitment platform.

      Return type:
         "bool"

   shows_reward_by_default = False

      Whether participants are shown their accumulated reward when the
      experiment does not say either way. Recruiters that disburse
      money through a platform show it; local and generic recruitment
      does not, because in those cases PsyNet cannot pay anyone and
      quoting a figure promises something the experimenter has to
      honour by hand.

   supports_max_concurrent_participants = True

      Whether "max_concurrent_participants" may hold newcomers on the
      start page. Only open-link recruiters support it; see
      "psynet.capacity".

class psynet.recruiters.LabRecruiter(*args, **kwargs)

   Bases: "BaseLabRecruiter"

   The production lab-recruiter.

class psynet.recruiters.LabRecruitmentStatus(recruiter_name, participant_status_counts, study_id, study_status, study_cost, currency)

   Bases: "RecruitmentStatus"

exception psynet.recruiters.LucidIdentifierMismatch

   Bases: "Exception"

   A request's Lucid identifiers name different respondents.

class psynet.recruiters.LucidRID(*args, **kwargs)

   Bases: "Base", "SQLMixin"

   Lucid survey entrant, keyed by Lucid's respondent ID ("rid").

   Rows may exist before (or without) a PsyNet "Participant". When a
   participant is created with "worker_id == rid", "participant_id" is
   linked. Export separates identifying Lucid fields into
   "lucid_entrant_identifiers.csv" for ghost entrants.

   creation_time = None

      the time at which the Network was created.

   details

      a generic column for storing structured JSON data

   failed = None

      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 = None

      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...

   link_participant(participant)

      Associate this entrant with a Participant when one exists.

   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.

   resolve_participant()

      Return the linked participant, looking up by "rid" if needed.

      This method is read-only: it does not persist "participant_id".
      Durable linking happens at participant creation via
      "link_participant()".

   time_of_death = None

      the time at which failing occurred

   to_dict()

      Determines the information that is shown for this object in the
      dashboard.

   type

class psynet.recruiters.LucidRecruiter(*args, **kwargs)

   Bases: "BaseLucidRecruiter"

   The production Lucid recruiter. Recruit participants from the Lucid
   Marketplace.

exception psynet.recruiters.LucidRecruiterException

   Bases: "Exception"

   Custom exception for LucidRecruiter

class psynet.recruiters.LucidRecruitmentStatus(recruiter_name, participant_status_counts, study_id, study_status, study_cost, currency, survey_sid, survey_number, total_completes, total_entrants, total_screens, completion_loi, drop_off_rate, conversion_rate, incidence_rate, payment_per_hour, exchange_rate, cost_per_survey, earnings_per_click, system_conversion, termination_loi, last_complete_date, config)

   Bases: "RecruitmentStatus"

class psynet.recruiters.LucidStatus(*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 = None

      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 = None

      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 = None

      the time at which failing occurred

   to_dict()

      Determines the information that is shown for this object in the
      dashboard.

   type

class psynet.recruiters.MockLucidRecruiter(*args, **kwargs)

   Bases: "MockRecruiter", "BaseLucidRecruiter"

   register_study(**kwargs)

      Register a study with the mock recruiter.

      This method is a placeholder and does not register any actual
      recruitment.

      Parameters:
         ****kwargs** -- Additional keyword arguments for study
         registration, e.g. study_id.

class psynet.recruiters.MockProlificRecruiter(*args, **kwargs)

   Bases: "PsyNetRecruiterMixin", "MockProlificRecruiter"

psynet.recruiters.PROLIFIC_DEFAULT_UNSUCCESSFUL_BASE_PAYMENT = 0.25

   Default fixed screen-out reward (in currency units) paid to
   unsuccessful participants. Prolific requires this to be strictly
   less than the study's base payment, so studies with "base_payment
   <= 0.25" must set "prolific_unsuccessful_base_payment" explicitly
   (or disable the feature).

class psynet.recruiters.PlatformPaymentView(supported, bonus=None, submission_status=None)

   Bases: "object"

   What the recruitment platform currently reports for a participant.

   "supported" is False when this recruiter cannot poll. "bonus" is
   "None" when a supported lookup failed. Prolific pay is
   asynchronous, so "bonus" can lag a successful POST.

class psynet.recruiters.ProlificRecruiter(*args, **kwargs)

   Bases: "PsyNetProlificRecruiterMixin", "ProlificRecruiter"

   open_recruitment(n=1)

      Create the Prolific study, adding guidance when creation fails
      while screen-out payment is enabled.

      Prolific's FIXED_SCREEN_OUT_PAYMENT action is documented as
      workspace-gated, and screen-out payment is enabled by default in
      PsyNet, so a workspace lacking the gate would fail here with an
      otherwise cryptic Prolific error.

      Return type:
         "dict"

class psynet.recruiters.PsyNetExitPageMixin

   Bases: "object"

   PsyNet's final page, for recruiters that have no exit page of their
   own.

   Dallinger's "exit_recruiter.html" is the one participant-facing
   page that never picked up the participant theme, and it showed the
   recruiter's Python class name above a table of raw payment fields,
   including a bare "None" bonus on recruiters that never pay one. It
   cannot be replaced by shipping a template of the same name, because
   Dallinger's "extra_files" mechanism does not overwrite templates
   Dallinger already provides, so PsyNet renders its own template
   instead.

   Mix this in only for recruiters that do not need a platform
   submission control. Prolific renders a separate PsyNet-themed
   wrapper around its submission behavior; Lucid redirects through its
   own flow.

class psynet.recruiters.PsyNetProlificRecruiterMixin

   Bases: "PsyNetRecruiterMixin"

   approve_hit(assignment_id)

      COMPLETE an ACTIVE/TIMED-OUT row, or Approve one already
      AWAITING REVIEW.

   assignment_returned_logic()

      Create the TimelineLogic for checking assignment return status.

      Return type:
         "Union"["Elt", "List"["Elt"], "EltCollection"]

   can_report_apparent_bonus()

      Prolific submissions expose "bonus_payments" on GET.

      Return type:
         "bool"

   static check_assignment_return_status(participant)

      Check and update the participant's assignment return status via
      API call.

      Returns:
         True if assignment is returned, False otherwise

      Return type:
         bool

   check_for_returned_assignment(participant)

      Check if the participant has returned the assignment.

      Return type:
         "bool"

   static check_screen_out_config(config)

      Deploy-time validation of the Prolific screen-out payment
      feature.

      Only applies when deploying with a Prolific recruiter and the
      feature is enabled ("prolific_pay_unsuccessful", on by default).
      Validates the (explicit or default) fixed reward against
      "base_payment" and requires "prolific_screen_out_slots" to be
      set explicitly, since it caps the study's worst-case screen-out
      spend.

   property completion_codes_and_actions: list[dict]

      Add researcher-actor DEFAULT and, when enabled, researcher-actor
      UNSUCCESSFUL.

   completion_status(participant)

      Return the payment-path status for this Prolific participant.

      "returned" is trusted once the return-for-bonus flow has
      recorded it. If an exit completion code was issued, that
      snapshot is preferred over the current "failed" flag, so a later
      fail cannot reclassify a participant who already left with the
      auto-approving code.

      Return type:
         "str"

   confirm_recorded_submission(participant)

      Show that Prolific submission is finished; do not ask again.

      Return type:
         "Union"["Elt", "List"["Elt"], "EltCollection"]

   decide_payment(participant, *, experiment)

      Use the committed plan's payment decision when it is complete.

      Return type:
         "PaymentDecision"

   error_page_presentation(*, participant=None, plan=None, assignment_id=None, external_submit_url=None, contact_address=None)

      Explain Prolific's support or payment path after an error.

      Return type:
         "ErrorRecoveryPresentation"

   exit_code_type(participant)

      Return the completion-code type issued at local submit.

      Unsuccessful participants get the UNSUCCESSFUL code, which
      triggers Prolific's fixed screen-out payment. "None" selects the
      recruiter's default (auto-approving) code. The issued type is
      stored for later payment and for the researcher-actor "COMPLETE"
      call; participants are not sent to a completion-code URL.

   exit_response(experiment, participant)

      Stay on a PsyNet page; stamp the issued completion code.

      After Submit, reload this route so the confirmation is a new
      document rather than a rewrite of the submit heading.

      Return type:
         "str"

   issue_unsuccessful_completion_code(participant)

      Record that this failed participant is leaving with the screen-
      out code.

      Called from submission-complete (the error-page Submit button
      POSTs "/prolific-submission-listener", which enqueues that
      handler). Rendering the error page must not write this field:
      viewing the page without submitting would otherwise classify
      later payment as "screened_out". First issuance wins: a
      different already-issued code is left alone.

      Returns True if the unsuccessful code is now recorded.

      Return type:
         "bool"

   open_recruitment(n=1)

      Create the Prolific study, adding guidance when creation fails
      while screen-out payment is enabled.

      Prolific's FIXED_SCREEN_OUT_PAYMENT action is documented as
      workspace-gated, and screen-out payment is enabled by default in
      PsyNet, so a workspace lacking the gate would fail here with an
      otherwise cryptic Prolific error.

      Return type:
         "dict"

   property pays_unsuccessful_participants_via_screen_out

      Whether unsuccessful (failed or errored) participants are paid
      automatically via a Prolific screen-out completion code.

   plan_exit(experiment, participant, context)

      Plan Prolific's submission and payment outcome.

      Return type:
         "ExitPlan"

   platform_base_for(status, experiment)

      Base amount Prolific pays for this payment status.

      Return type:
         "float"

   platform_payment_view(participant)

      Read Prolific submission status and "bonus_payments".

      Uses Dallinger's "get_participant_submission(...,
      translate=False)" so "bonus_payments" are kept and a miss is not
      a recruitment error. Pay is asynchronous, so bonus can lag a
      POST.

      For participants paid via the screen-out completion code, the
      fixed screen-out reward is excluded from "bonus", so the
      reported figure is comparable to PsyNet's own top-up bonus (see
      "_without_screen_out_reward").

      Return type:
         "PlatformPaymentView"

   release_early_exit_without_payment(participant)

      Ask the participant to return the Prolific submission without
      pay.

      Return type:
         "Union"["Elt", "List"["Elt"], "EltCollection"]

   render_submission_page(participant)

      Render the Submit/confirmation document without writing payment
      state.

      "RecordedSubmissionPage" calls this from the read-only timeline
      render, where the submission handler has already stamped the
      completion code.

      Return type:
         "str"

   request_return_for_bonus(participant)

      Ask the participant to return their Prolific submission and pay
      them via bonus (or, if returns are disabled, ask them to message
      the experimenter). Used for failed participants who are not
      covered by the screen-out completion code.

      Return type:
         "Union"["Elt", "List"["Elt"], "EltCollection"]

   retry_unpaid_platform_bases()

      Retry COMPLETE/Approve for participants whose study base is
      still unpaid.

      Return type:
         "None"

   return_and_message_experimenter_logic()

      Ask them to return on Prolific and message the researcher.

      Return type:
         "Union"["Elt", "List"["Elt"], "EltCollection"]

   return_for_bonus_logic(enable_return_for_bonus)

      Return-on-Prolific instructions, without a second intro page.

      Return type:
         "Union"["Elt", "List"["Elt"], "EltCollection"]

   static reward_and_set_bonus(participant)

      Pay a returned participant from the same decision/record/pay
      path.

   reward_bonus(participant, amount, reason)

      Pay a Prolific bonus. Return False if Prolific rejected the
      transfer.

   property screen_out_slots

      The maximum number of screen-out payments Prolific will make
      before pausing the study (see the "prolific_screen_out_slots"
      config parameter).

      Must be set explicitly: deploy-time validation
      ("check_screen_out_config") requires it whenever screen-out
      payment is enabled, and there is no silent runtime default.

   shows_error_recovery_page(plan)

      Prolific recovery asks the participant to submit or return.

      Return type:
         "bool"

   property tops_up_unsuccessful_participants: bool

      Whether participants paid via the screen-out completion code are
      topped up to their full accumulated reward with a bonus (see the
      "prolific_unsuccessful_topup" config parameter). When disabled,
      only performance rewards are paid on top of the fixed payment.

   total_owed(participant, status, platform_base)

      Total compensation for this Prolific participant.

      When screen-out top-up is disabled, time rewards are forfeited
      and only the fixed screen-out amount plus any performance reward
      is owed.

      Return type:
         "float"

   property unsuccessful_base_payment

      The fixed screen-out reward (in currency units) paid to
      unsuccessful participants via a Prolific completion code, or
      "None" if the feature is disabled via "prolific_pay_unsuccessful
      = false".

      Defaults to "PROLIFIC_DEFAULT_UNSUCCESSFUL_BASE_PAYMENT" (0.25);
      override with "prolific_unsuccessful_base_payment".

   verify_status_of(participants)

      Sync participant statuses with Prolific, or skip if no study is
      recorded.

      No study ID is recorded when PsyNet did not open the study
      itself (for example with "auto_recruit = false", including debug
      runs), so there are no submissions to compare against. The clock
      runs this check every few seconds, so the skip is logged only
      once per process.

class psynet.recruiters.PsyNetRecruiterMixin

   Bases: "object"

   PsyNet behavior shared by all recruiters, including payment and
   early exit.

   after_rejected_consent(experiment, participant)

      Hook run when the participant rejects consent and never reaches
      submission.

      PsyNet runs it in a worker process after the participant's
      request commits, without making them wait, so it may call the
      recruitment platform. It has no Flask request context.

   apparent_bonus_paid(participant)

      Bonus the platform currently reports as paid, or "None" if
      unknown.

      A return of "0.0" means the platform reports no bonus yet.
      "None" means this recruiter cannot tell, or the lookup failed.
      Prolific pay is asynchronous, so a successful POST can still
      look unpaid for a while.

      Return type:
         "Optional"["float"]

   can_report_apparent_bonus()

      Whether this recruiter can poll the platform for bonuses already
      paid.

      Return type:
         "bool"

   check_consents(consents)

      Check that the consent elements are suitable for the recruiter.
      By default this check is skipped in "psynet debug local".

      Parameters:
         **consents** (*list*) -- List of consent objects from the
         timeline

   completion_status(participant)

      Return the payment-path status for this participant.

      "returned" and "screened_out" are trusted once recorded.
      Otherwise the default is "approved" (the platform pays the full
      study base).

      Return type:
         "str"

   decide_payment(participant, *, experiment)

      Decide status, platform base, and bonus without writing or
      paying.

      Return type:
         "PaymentDecision"

   early_exit_allowed(participant)

      Return whether this participant may leave with the paid outcome.

      Unpaid recruiters always allow leave. Paid recruiters require
      the configured reward threshold unless a subclass (e.g. Lucid)
      overrides.

      Return type:
         "bool"

   error_page_presentation(*, participant=None, plan=None, assignment_id=None, external_submit_url=None, contact_address=None)

      Describe error-page copy and any recruiter handoff.

      Return type:
         "ErrorRecoveryPresentation"

   execute_early_exit_plan(experiment, participant, plan)

      Execute a server-owned early-exit plan.

      Marks the participant as having left and fails them without
      entering "unsuccessful_end". Callers choose the terminal branch
      afterwards.

      Return type:
         "None"

   gates_early_exit_on_reward()

      Return whether paid early exit requires the reward threshold.

      Recruiters that do not pay through PsyNet never gate on reward:
      leaving simply ends the session. Lucid overrides
      "early_exit_allowed()" instead, because termination must always
      be available.

      Return type:
         "bool"

   has_external_bonus_payment()

      Whether bonuses are paid through an external recruitment
      platform.

      Local debug recruiters such as HotAir have no platform, so
      payment review and platform status are hidden for them.

      Return type:
         "bool"

   plan_exit(experiment, participant, context)

      Plan one terminal participant outcome.

      Voluntary Leave, error recovery, and timeline endings share this
      entry point while retaining context-specific policy and
      presentation.

      Return type:
         "ExitPlan"

   platform_base_for(status, experiment)

      Base amount the recruitment platform pays for this payment
      status.

      Return type:
         "float"

   platform_payment_view(participant)

      Return the platform's current bonus and submission status, if
      any.

      Return type:
         "PlatformPaymentView"

   prepare_error_recovery(participant)

      Perform recruiter bookkeeping before rendering error recovery.

      Return type:
         "None"

   record_payment(participant, decision)

      Write the payment decision onto the participant (no money
      transfer).

      Return type:
         "None"

   release_early_exit_without_payment(participant)

      Tell the participant how to finish without payment.

      Return type:
         "Union"["Elt", "List"["Elt"], "EltCollection"]

   report_submission_outcome(participant, amount, reason)

      Report the terminal outcome, transferring a real bonus if
      needed.

      Most recruiters have no separate outcome callback, so sub-cent
      amounts are a no-op and real bonuses use "reward_bonus".
      Recruiters whose bonus endpoint is also their terminal outcome
      callback can override this method to report every amount,
      including zero. Raises inside timeline steps, even for sub-cent
      amounts.

   reward_bonus(participant, amount, reason)

      Transfer a bonus. Return False if the platform rejected the
      transfer.

      Dallinger helpers often return "None" on success. "None" or any
      value other than "False" is treated as success.

   shows_error_recovery_page(plan)

      Return whether tracked fatal recovery presents a participant
      page.

      Generic, HotAir, and lab recruiters have nothing to ask after an
      error, so PsyNet commits the plan on the server without a
      Continue or Submit control. The participant still sees that an
      error occurred. Do not infer this from "button_label is None".
      Custom recruiters that present recovery UI must override this
      method; a custom "error_page_presentation" with a button is not
      enough.

      Return type:
         "bool"

   shows_reward_by_default = True

      Whether participants are shown their accumulated reward when the
      experiment does not say either way. Recruiters that disburse
      money through a platform show it; local and generic recruitment
      does not, because in those cases PsyNet cannot pay anyone and
      quoting a figure promises something the experimenter has to
      honour by hand.

   supports_max_concurrent_participants = False

      Whether "max_concurrent_participants" may hold newcomers on the
      start page. Only open-link recruiters support it; see
      "psynet.capacity".

   total_owed(participant, status, platform_base)

      Total compensation PsyNet intends the participant to receive.

      Return type:
         "float"

psynet.recruiters.StagingCapRecruiter

   alias of "StagingLabRecruiter"

class psynet.recruiters.StagingLabRecruiter(*args, **kwargs)

   Bases: "BaseLabRecruiter"

   The staging lab-recruiter.

psynet.recruiters.configured_recruiter_class(config=None)

   Return the recruiter class that the configuration selects.

   This mirrors "dallinger.recruiters.from_config()" without
   instantiating the recruiter, which can be expensive (for example,
   building a Prolific API client). Use it when only the recruiter
   type matters.

   Parameters:
      **config** -- Dallinger configuration; defaults to the active
      configuration.

   Returns:
      The recruiter class, or "None" if the configured name is unknown
      in debug mode (where "from_config" also returns "None").

   Return type:
      class or None

psynet.recruiters.get_lucid_settings(lucid_recruitment_config_path, termination_time_in_s, bid_incidence=66, collects_pii=False, inactivity_timeout_in_s=120, no_focus_timeout_in_s=60, aggressive_no_focus_timeout_in_s=3, initial_response_within_s=180, debug_recruiter=False)

   Parameters:
      * **lucid_recruitment_config_path** (*str**, **path to the Lucid
        recruitment config.*)

      * **termination_time_in_s** (*int**, **maximal time a
        participant can spend on the experiment. If this time is
        exceeded**,*) -- the participant is terminated via the front-
        end. If the participant has closed the tab, the recruiter
        clock terminates them one minute later instead.

      * **bid_incidence** (*int**, **default 66**, **the bid
        incidence. Bid incidence is the number** of
        **completes/**(**number** of **completes +*) -- participants
        who did not pass the qualifications). It is a percentage, so
        if you expect 66% of the participants to pass the
        qualifications, set it to 66. Set it to a realistic value, but
        as high as possible.

      * **collects_pii** (*bool**, **default False**, **whether the
        survey collects personally identifiable information.*)

      * **inactivity_timeout_in_s** (*int**, **default 120**, **the
        inactivity timeout in seconds. If the participant is inactive
        for*) -- this amount of time, the participant is terminated
        via the front-end. Inactive means that the participant does
        not interact with the page (i.e., no ["click", "keypress",
        "load", "mousedown", "mousemove", "touchstart"]).

      * **no_focus_timeout_in_s** (*int**, **default 60**, **the no
        focus timeout in seconds. If the participant moves the mouse
        outside*) -- the window or opens another tab, the participant
        is terminated via the front-end after this amount of time.

      * **aggressive_termination_on_no_focus** (int, default 3, this
        the same setting as *no_focus_timeout_in_s*, but it is) --
        only used for aggressive in the consent page, since many
        participants are lost there.

      * **initial_response_within_s** (*int**, **default 180 seconds**
        (**3 minutes**)**. If the participant does not proceed to the
        consent*) -- within this time, the participant is terminated
        via the backend-end.

      * **debug_recruiter** (*bool**, **default False**, **whether to
        use the development recruiter. This is useful for local
        testing.*)

psynet.recruiters.latest_participant_for_assignment(assignment_id)

   Return the most recent participant with this assignment id, or
   "None".

   Unlike "Experiment.get_participant_from_assignment_id", this lookup
   is tolerant: it returns "None" when no participant matches and the
   newest row when several do, making it suitable for best-effort
   contexts such as error pages and approval hooks.

psynet.recruiters.named_recruiter_class(config=None)

   Return the class of the recruiter named in the configuration, or
   "None".

   Unlike "configured_recruiter_class()", this ignores the debug-mode
   stand-in and replay mode, so it gives the recruiter that a
   deployment will use. It returns "None" when no recruiter is named
   or the name is unknown.

psynet.recruiters.recruits_real_participants(config=None)

   Return why the configured recruitment may bring real participants,
   or "None".

   Live mode and any recruiter other than the test ones (development
   and mock recruiters, Hot Air, generic, bots and simulated
   participants) may bring real participants.
