@lango-project/lango-boss 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +2 -0
  3. package/README.md +118 -2
  4. package/dist/.lango/bignumber.mjs +3119 -0
  5. package/dist/.lango/entries/cli.mjs +139 -0
  6. package/dist/.lango/entries/cli.mjs.map +1 -0
  7. package/dist/.lango/localization.mjs +108 -0
  8. package/dist/.lango/runtime.mjs +725 -0
  9. package/dist/.lango/vendor/i18next.LICENSE +21 -0
  10. package/dist/.lango/vendor/i18next.mjs +2434 -0
  11. package/dist/.lango/xmldom/conventions.js +429 -0
  12. package/dist/.lango/xmldom/dom-parser.js +591 -0
  13. package/dist/.lango/xmldom/dom.js +3759 -0
  14. package/dist/.lango/xmldom/entities.js +2171 -0
  15. package/dist/.lango/xmldom/errors.js +205 -0
  16. package/dist/.lango/xmldom/grammar.js +559 -0
  17. package/dist/.lango/xmldom/index.js +41 -0
  18. package/dist/.lango/xmldom/package.json +1 -0
  19. package/dist/.lango/xmldom/sax.js +983 -0
  20. package/dist/.lango/xmldom.LICENSE.md +8 -0
  21. package/dist/boss.mjs +136 -0
  22. package/dist/boss.mjs.map +1 -0
  23. package/dist/claim_watch.mjs +99 -0
  24. package/dist/claim_watch.mjs.map +1 -0
  25. package/dist/cli.mjs +7 -0
  26. package/dist/cli.mjs.map +1 -0
  27. package/dist/configuration.mjs +58 -0
  28. package/dist/configuration.mjs.map +1 -0
  29. package/dist/dispatcher.mjs +108 -0
  30. package/dist/dispatcher.mjs.map +1 -0
  31. package/dist/driver.mjs +98 -0
  32. package/dist/driver.mjs.map +1 -0
  33. package/dist/envelope.mjs +92 -0
  34. package/dist/envelope.mjs.map +1 -0
  35. package/dist/library.mjs +139 -0
  36. package/dist/library.mjs.map +1 -0
  37. package/dist/management.mjs +360 -0
  38. package/dist/management.mjs.map +1 -0
  39. package/dist/management_transaction.mjs +26 -0
  40. package/dist/management_transaction.mjs.map +1 -0
  41. package/dist/namespace.mjs +27 -0
  42. package/dist/namespace.mjs.map +1 -0
  43. package/dist/queue.mjs +161 -0
  44. package/dist/queue.mjs.map +1 -0
  45. package/dist/reads.mjs +359 -0
  46. package/dist/reads.mjs.map +1 -0
  47. package/dist/retention.mjs +133 -0
  48. package/dist/retention.mjs.map +1 -0
  49. package/dist/schedule_sync.mjs +222 -0
  50. package/dist/schedule_sync.mjs.map +1 -0
  51. package/dist/schedule_transaction.mjs +24 -0
  52. package/dist/schedule_transaction.mjs.map +1 -0
  53. package/dist/schedules.mjs +201 -0
  54. package/dist/schedules.mjs.map +1 -0
  55. package/dist/transaction.mjs +16 -0
  56. package/dist/transaction.mjs.map +1 -0
  57. package/dist/validation.mjs +90 -0
  58. package/dist/validation.mjs.map +1 -0
  59. package/dist/worker.mjs +316 -0
  60. package/dist/worker.mjs.map +1 -0
  61. package/docs/guide.md +88 -0
  62. package/docs/management.md +93 -0
  63. package/docs/producer.md +115 -0
  64. package/docs/reads.md +107 -0
  65. package/docs/reference.md +77 -0
  66. package/docs/release.md +103 -0
  67. package/docs/retention.md +47 -0
  68. package/docs/scheduling.md +79 -0
  69. package/docs/worker.md +90 -0
  70. package/examples/reports/README.md +118 -0
  71. package/examples/reports/app.lango +133 -0
  72. package/examples/reports/deploy.xml +6 -0
  73. package/examples/reports/dist/.lango/bignumber.mjs +3119 -0
  74. package/examples/reports/dist/.lango/entries/app.mjs +133 -0
  75. package/examples/reports/dist/.lango/entries/app.mjs.map +1 -0
  76. package/examples/reports/dist/.lango/localization.mjs +108 -0
  77. package/examples/reports/dist/.lango/runtime.mjs +725 -0
  78. package/examples/reports/dist/.lango/vendor/i18next.LICENSE +21 -0
  79. package/examples/reports/dist/.lango/vendor/i18next.mjs +2434 -0
  80. package/examples/reports/dist/.lango/xmldom/conventions.js +429 -0
  81. package/examples/reports/dist/.lango/xmldom/dom-parser.js +591 -0
  82. package/examples/reports/dist/.lango/xmldom/dom.js +3759 -0
  83. package/examples/reports/dist/.lango/xmldom/entities.js +2171 -0
  84. package/examples/reports/dist/.lango/xmldom/errors.js +205 -0
  85. package/examples/reports/dist/.lango/xmldom/grammar.js +559 -0
  86. package/examples/reports/dist/.lango/xmldom/index.js +41 -0
  87. package/examples/reports/dist/.lango/xmldom/package.json +1 -0
  88. package/examples/reports/dist/.lango/xmldom/sax.js +983 -0
  89. package/examples/reports/dist/.lango/xmldom.LICENSE.md +8 -0
  90. package/examples/reports/dist/app.mjs +7 -0
  91. package/examples/reports/dist/app.mjs.map +1 -0
  92. package/examples/reports/dist/handlers.mjs +202 -0
  93. package/examples/reports/dist/handlers.mjs.map +1 -0
  94. package/examples/reports/dist/setup.mjs +14 -0
  95. package/examples/reports/dist/setup.mjs.map +1 -0
  96. package/examples/reports/handlers.lango +153 -0
  97. package/examples/reports/jobs.xml +5 -0
  98. package/examples/reports/package.json +23 -0
  99. package/examples/reports/routes.xml +4 -0
  100. package/examples/reports/setup.lango +17 -0
  101. package/package.json +62 -4
  102. package/src/boss.lango +92 -0
  103. package/src/claim_watch.lango +58 -0
  104. package/src/cli.lango +103 -0
  105. package/src/configuration.lango +43 -0
  106. package/src/dispatcher.lango +75 -0
  107. package/src/driver.lango +72 -0
  108. package/src/envelope.lango +56 -0
  109. package/src/library.lango +66 -0
  110. package/src/management.lango +302 -0
  111. package/src/management_transaction.lango +28 -0
  112. package/src/namespace.lango +15 -0
  113. package/src/queue.lango +115 -0
  114. package/src/reads.lango +277 -0
  115. package/src/retention.lango +107 -0
  116. package/src/schedule_sync.lango +190 -0
  117. package/src/schedule_transaction.lango +22 -0
  118. package/src/schedules.lango +165 -0
  119. package/src/transaction.lango +23 -0
  120. package/src/validation.lango +45 -0
  121. package/src/worker.lango +230 -0
@@ -0,0 +1,115 @@
1
+ # Queue producer integration
2
+
3
+ The producer uses the application's PostgreSQL configuration from `deploy.xml`, job targets from `routes.xml`, and stable `package.json` name. It does not require a second database URL. SQLite is not supported by Boss.
4
+
5
+ ## Lifecycle
6
+
7
+ The public package exports `Boss` in addition to `loadConfiguration`.
8
+
9
+ | Method | Behavior |
10
+ | --- | --- |
11
+ | `new Boss(directory)` | Loads and validates application configuration without connecting. |
12
+ | `start()` | Opens the producer's control-plane pool, installs/migrates its pg-boss schema, and prepares registered queues. Returns a Promise. |
13
+ | `configure(builder)` | Registers the request-scoped queue factory on a Server Builder and returns that builder. Call after start resolves. |
14
+ | `executor(settings)` | Creates an HTTP-free Server Executor with the same queue integration. Settings must include its live identity provider. The caller starts/closes the executor. |
15
+ | `close()` | Closes the producer's control-plane pool. Returns a Promise; repeated close is safe. |
16
+
17
+ `start()` can only be called once. Producer startup does not consume jobs or activate schedules, supervision, or job handlers. The control-plane pool has two connections and uses Server's configured connection/query timeouts. Queue submission does not borrow one of these connections.
18
+
19
+ Each application uses a pg-boss schema derived from the SHA-256 hash of its package name (`lango_` followed by 32 hexadecimal characters). Applications sharing a database can use the same queue names without sharing job storage. Keep the application name stable across deployments. Initial schema setup requires the database role to be allowed to create the schema and its objects.
20
+
21
+ Close HTTP servers and executors before closing Boss. Those components own the active SQL scopes; closing the control-plane pool does not revoke already-created senders or undo committed jobs.
22
+
23
+ ## Server Builder
24
+
25
+ ```lango
26
+ import js "@lango-project/lango-boss" as boss
27
+ import js "@lango-project/lango-server" as server
28
+
29
+ createApplication(directory, settings)
30
+ producer = new boss/Boss(directory)
31
+ return chain producer.start()
32
+ then(ignored)
33
+ capture directory
34
+ capture settings
35
+ capture producer
36
+ builder = new server/Builder(directory)
37
+ builder.configure(settings)
38
+ producer.configure(builder)
39
+ builder.endpoint({
40
+ path: "/reports/request"
41
+ module: "@app/reports"
42
+ handler: "requestReport"
43
+ policy: "login"
44
+ })
45
+ return {
46
+ server: builder.build()
47
+ boss: producer
48
+ }
49
+ catch(error)
50
+ capture producer
51
+ return chain producer.close()
52
+ then(ignored)
53
+ capture error
54
+ throw error
55
+ ```
56
+
57
+ The caller starts the returned Server and closes both components during shutdown. Its Builder database settings must describe the same application database used by Boss. This initial integration takes job targets from the application's XML route configuration; adding HTTP endpoints to a Builder does not make them queue targets.
58
+
59
+ Server prepares `context queue` before Register, Validate, middleware, or the application handler runs. No Boss dependency is added to Server itself. The registered factory is loaded from the application's installed Boss package.
60
+
61
+ ## Sending
62
+
63
+ ```lango
64
+ requestReport(input)
65
+ context queue
66
+ id = queue.send("/reports/create", {
67
+ reportType: input.reportType
68
+ })
69
+ return {
70
+ jobId: id
71
+ }
72
+ ```
73
+
74
+ `send` is synchronous in application code and returns a job ID. It resolves an exact registered job path to its queue, checks the current token's policy and any password freshness requirement, and serializes the input as a JSON map. Unknown paths, invalid data, missing permission, stale authentication, closed SQL scopes, and database errors throw. The application controls the HTTP response; Boss does not require a special status or response envelope.
75
+
76
+ If a Lango transaction is active, the job insert uses that same PostgreSQL connection and transaction. It is invisible to other connections until commit, and a rollback removes it together with the application's writes. A nested rollback marks the transaction rollback-only as usual. A failed or rollback-only transaction cannot enqueue.
77
+
78
+ Without an active transaction, send opens and commits its own short transaction before returning. It does not wrap unrelated application writes in that transaction. Use an explicit Lango transaction to make those writes atomic with submission.
79
+
80
+ A job ID returned inside an active transaction is provisional until the caller commits. Returning from a handler with its transaction still open rolls back the job and fails the request. Retaining a sender after its request/job scope closes does not permit reuse.
81
+
82
+ If a commit loses its connection, propagate the failure and investigate the outcome; Boss does not automatically resend. The current implementation has no submission deduplication guarantee. Use application operation keys and idempotent handlers where retries or uncertain outcomes matter.
83
+
84
+ ## Source identity and envelope
85
+
86
+ The producer derives trusted source references from the current execution token. HTTP/user jobs contain clientId and, when present, userId/grantId. System executions contain their explicit identity profile. Job input cannot select the trusted source, queue, module, or handler. Input may itself contain fields called `source` or `policy`; they remain ordinary application data.
87
+
88
+ The version-1 internal envelope contains application name, path, input, trusted source, and failed-retention metadata. The framework does not copy browser JWTs, cookies, client proofs, old policy claims, or authenticatedAt into that envelope. An eventual consumer must still resolve live identity and authorization on every attempt.
89
+
90
+ Submissions specify three retries, a 10-second initial backoff, a 300-second backoff cap, 900-second expiration, and a 30-second heartbeat. The seven-day failed-retention value is stored as metadata and enforced by [Worker cleanup](retention.md); it is not mapped to pg-boss `retentionSeconds`. Boss disables native terminal deletion on these records so a different native terminal deadline cannot delete them early. The producer alone does not run cleanup or settle retries.
91
+
92
+ ## HTTP-free jobs
93
+
94
+ ```lango
95
+ createReport(input)
96
+ context queue
97
+ start_trans()
98
+ try
99
+ update = SQL
100
+ update reports set prepared = true where id = :id
101
+ update.id = input.id
102
+ update.execute()
103
+ childId = queue.send("/reports/deliver", {
104
+ reportId: input.id
105
+ })
106
+ commit_trans()
107
+ return childId
108
+ catch error
109
+ rollback_trans()
110
+ throw error
111
+ ```
112
+
113
+ Create the executor through `producer.executor(settings)` to prepare the sender after the attempt's live identity has been resolved. Job handlers and nested Lango callbacks then use queue just like HTTP handlers. No browser context or HTTP response is synthesized.
114
+
115
+ The producer prepares storage and sends jobs. The same queue scope provides owner-scoped `queue.get(id)`; package functions provide authorized listing/detail and [audited management operations](management.md). See [status and results](reads.md). [Worker](worker.md) provides consumption, settlement, schedule reconciliation, retention cleanup, and active claim interruption separately.
package/docs/reads.md ADDED
@@ -0,0 +1,107 @@
1
+ # Job status and results
2
+
3
+ Reads are synchronous Lango calls in the current handler's database and token scope. Configure the queue provider through `Boss.configure(builder)` for HTTP or `Boss.executor(settings)` for internal execution. Callbacks inherit the same context. No separate management connection, HTTP endpoint, or implicit administrator identity is created.
4
+
5
+ ## Owner access
6
+
7
+ ```lango
8
+ reportStatus(input)
9
+ context queue
10
+ return queue.get(input.jobId)
11
+ ```
12
+
13
+ `queue.get(jobId)` returns a status/result map or null. Reading requires all of:
14
+
15
+ - A version-1 Boss record for this application.
16
+ - A user source with the same client ID, user ID, and grant ID as the current token. Absent identity fields must match too.
17
+ - A target still registered on that path and physical queue.
18
+ - The target's policy and authentication-freshness conditions, evaluated against the current token.
19
+
20
+ Job IDs are not access credentials. Logging out, changing users on the same client, or changing grants does not transfer access to the previous identity's jobs. Anonymous jobs belong to the anonymous client context; logging in does not automatically transfer those jobs to the new authenticated identity. System jobs are available through authorized management reads, not owner reads. A management policy does not bypass ownership in `queue.get()`.
21
+
22
+ Invalid, missing, expired, ambiguous, foreign, and inaccessible job IDs all return null without identifying which condition applied. Closed database scopes and failed transactions throw instead of returning an apparent "not found" result.
23
+
24
+ The scope's token must already represent the application's trusted authorization decision. Boss does not know application user/grant tables or invoke HTTP Validate/guard itself. HTTP applications must perform their normal live ban, revocation, and authorization checks before exposing reads. Internal Executor calls already perform their configured live identity preparation on each attempt. A retained queue object must not be reused in another request.
25
+
26
+ ## Management access
27
+
28
+ Import the package namespace for management reads:
29
+
30
+ ```lango
31
+ import js "@lango-project/lango-boss" as boss
32
+
33
+ listJobs(input)
34
+ return boss/jobs({
35
+ queue: input.queue
36
+ path: input.path
37
+ state: input.state
38
+ limit: input.limit
39
+ cursor: input.cursor
40
+ })
41
+
42
+ jobDetail(input)
43
+ return boss/job(input.jobId)
44
+ ```
45
+
46
+ These are package functions; `Boss(directory)` remains the producer lifecycle object. They use the current queue context and require the token's explicit `boss.manage` policy on every call. The policy does not grant itself and cannot be supplied in list options. A system identity must also be assigned it explicitly by the application identity provider.
47
+
48
+ Management denial throws before looking up a record. Boss does not choose an HTTP status or create a login challenge; the application handles that boundary. Authorized `boss/job(id)` returns null for a missing or invalid ID. It can inspect historical jobs whose route has since been removed, but never another application's records.
49
+
50
+ ## Return maps
51
+
52
+ Every job summary contains:
53
+
54
+ | Field | Meaning |
55
+ | --- | --- |
56
+ | `id` | Job UUID. |
57
+ | `queue` / `path` | Physical queue and stored internal target path. |
58
+ | `state` | Native `created`, `retry`, `active`, `completed`, `cancelled`, or `failed`. |
59
+ | `retryCount` / `retryLimit` | Native retry metadata; retry count is not a count of successful handler invocations. |
60
+ | `createdAt` / `startAfter` | UTC timestamps as strings, preserving PostgreSQL microseconds. |
61
+ | `startedAt` / `completedAt` | UTC timestamp strings or null when unset. |
62
+
63
+ Owner and management detail add `resultAvailable`, `result`, and `error`:
64
+
65
+ - `resultAvailable` is true only for a completed job with a recognized stored result envelope. `result` preserves null, false, numbers, strings, arrays, and maps.
66
+ - A queued job and a completed job without a recognized stored result both have `resultAvailable: false`. Do not infer result availability from null alone.
67
+ - A terminal controlled failure can return `error: { code, permanent }`. Native exception messages, stacks, and unrecognized output formats are not exposed. Other cases have `error: null`.
68
+
69
+ Management detail additionally returns stored `input` and a `source` map restricted to identity references (`kind`, `clientId`, `userId`, `grantId`, `identity`). Owner detail omits both fields. Lists contain only summaries: they do not select input, output, or source payloads from PostgreSQL. There is no `output` field in the public contract.
70
+
71
+ Management input/result data can contain application secrets; expose detail only through appropriately authorized application flows. These reads do not redact application-defined JSON fields or automatically emit a management-access audit record.
72
+
73
+ ## Filters and pagination
74
+
75
+ `boss/jobs(options)` accepts only the following optional fields:
76
+
77
+ | Option | Default | Meaning |
78
+ | --- | --- | --- |
79
+ | `queue` | null | Exact physical queue name. |
80
+ | `path` | null | Exact stored target path. |
81
+ | `state` | null | One supported native state. |
82
+ | `limit` | 50 | Integer from 1 to 200. |
83
+ | `cursor` | null | `nextCursor` returned by a previous page. |
84
+
85
+ It returns `{ items, nextCursor }`. Null `nextCursor` means there was no further row when the page was read. There is no total count or offset option. Unknown fields and invalid bounds/cursors throw. Filter values are bound SQL parameters, not SQL fragments.
86
+
87
+ Ordering is newest first by exact creation timestamp, UUID, and queue name. A cursor carries that position rather than requiring its original row to still exist, so retention or deletion of the anchor does not break traversal. Equal timestamps are disambiguated by the remaining keys. The cursor is bound to the application and the queue/path/state filter values; preserve those filters on following pages. The page size may change.
88
+
89
+ Cursors are opaque navigation data, not secrets, signatures, or authorization grants. Authorization is checked again for every page. They do not hold a database snapshot: newly inserted jobs ahead of the cursor appear on a fresh traversal, while concurrent state changes and deletion can change which later records match.
90
+
91
+ ## SQL and lifecycle
92
+
93
+ Reads use the queue context's existing PostgreSQL scope, including its transaction. A handler can read its own uncommitted submission; rollback removes that job. Queries explicitly qualify the application schema and leave the application's `search_path` unchanged. No transaction is implicitly started or committed by reading.
94
+
95
+ Scope checks happen on every call. Reusing a sender after its request/job scope closes throws `DatabaseScopeClosed`; a failed/rollback-only transaction is also rejected. Database failures propagate, rather than being disguised as an empty list or null.
96
+
97
+ The SQL adapter targets the pinned pg-boss schema. These internal table queries are not an application extension API. See [management](management.md) for retry, cancel, queue/schedule operations, and transactional mutation auditing. Read-access audit logging remains application-managed.
98
+
99
+ Page limits bound returned summaries, not database scan cost. Large histories and frequent status polling still need query-plan/index measurements for the application's workload; this step does not add a secondary status registry or performance benchmark.
100
+
101
+ ## Verification
102
+
103
+ ```sh
104
+ LANGO_TEST_POSTGRES='postgresql://user@127.0.0.1/test_database' npm run test:reads
105
+ ```
106
+
107
+ The real PostgreSQL tests use Executor's actual token/provider/database lifecycle. They cover identity changes, grants, permission loss and freshness, anonymous/system boundaries, foreign records, safe result projection, package management functions, page bounds, exact timestamp ordering, deleted cursors, transaction visibility, unchanged application schema lookup, and stale scope rejection. They are also part of `test:postgres`.
@@ -0,0 +1,77 @@
1
+ # API reference
2
+
3
+ All management functions use the current trusted queue/database/token scope. Their authorization is not provided by possession of a job ID. Unless described as asynchronous, these are synchronous Lango calls.
4
+
5
+ ## Package exports
6
+
7
+ | Export | Contract |
8
+ | --- | --- |
9
+ | `loadConfiguration(directory)` | Read and validate package/deployment/job/schedule configuration without opening PostgreSQL or starting handlers. Returned database settings may contain credentials. |
10
+ | `Boss(directory)` | Producer lifecycle object. |
11
+ | `Worker(directory, settings)` | Consumer lifecycle object with mandatory live identity provider. |
12
+ | `jobs(options = null)` | `boss.manage` list returning `{ items, nextCursor }`; queue/path/state filters, limit 1–200 (default 50), opaque cursor. |
13
+ | `job(id)` | `boss.manage` detail/result including input and restricted identity references, or null. |
14
+ | `retry(id)` | `boss.manage` mutation; only failed jobs receive one extra native attempt. |
15
+ | `cancel(id)` | `boss.manage` mutation; created/retry/active become cancelled. Active cancellation is a request, not stop acknowledgement. |
16
+ | `queues(options = null)` | `boss.manage` inventory of owned queues, pause state, and queued/active/failed counts. |
17
+ | `schedules(options = null)` | `boss.manage` inventory of currently present definitions and effective enabled state. |
18
+ | `pauseQueue(name)` / `resumeQueue(name)` | Persistently control new fetches; submission and already fetched jobs continue. |
19
+ | `pauseSchedule(name)` / `resumeSchedule(name)` | Change the persistent operational pause flag under the reconciliation lock; resume cannot override XML disabled state. |
20
+
21
+ Queue/schedule inventories accept limit 1–200 (default 50) and a returned name cursor. Mutations join an existing usable transaction or use a short one of their own; audit rows commit/rollback with the state change. See [management return maps and transitions](management.md).
22
+
23
+ Subpath exports `./queue`, `./transaction`, `./schedule-transaction`, and `./management-transaction` are trusted framework integration hooks. They are not request-body plugin selectors or a substitute for public authorization checks.
24
+
25
+ ## Boss instance
26
+
27
+ | Method | Result |
28
+ | --- | --- |
29
+ | `start()` | Promise; migrate/prepare storage and registered queues. One start per instance. |
30
+ | `configure(builder)` | Attach the queue provider to an existing Server builder; return builder. Requires started Boss. |
31
+ | `executor(settings)` | Create a Server Executor with the queue provider. Caller owns its start/close lifecycle. |
32
+ | `close()` | Promise; stop the producer driver. Repeated close is safe. |
33
+
34
+ `start()` does not consume jobs, activate schedules, or run cleanup. [Producer details](producer.md).
35
+
36
+ ## Worker instance
37
+
38
+ `start()` and `close()` return Promises. Worker prepares queues, system-profile checks, revision reconciliation, startup retention, and then activates consumption/scheduling. Close stops fetches and drains execution/settlement. See [worker settings](worker.md#embedded-consumer) for bounds.
39
+
40
+ | Setting | Default |
41
+ | --- | --- |
42
+ | `identity: { module, handler }` | Required. |
43
+ | `workers` | 2. |
44
+ | `pollingIntervalSeconds` | 2. |
45
+ | `heartbeatRefreshSeconds` | Native automatic interval. |
46
+ | `cronMonitorIntervalSeconds` | 30. |
47
+ | `cleanupIntervalSeconds` | 60. |
48
+ | `cleanupBatchSize` | 1000. |
49
+ | `startupTimeoutMs` / `shutdownTimeoutMs` | 30000 each. |
50
+
51
+ Per-attempt expiration comes from trusted claimed-job metadata. Claim checks run about once per second per local dispatched job. A process shutdown deadline, application SQL timeout, native lease supervision, and the handler expiration are distinct bounds.
52
+
53
+ ## Queue context
54
+
55
+ | Call | Contract |
56
+ | --- | --- |
57
+ | `queue.send(path, input)` | Validate exact registered target, JSON map input, current target policy/freshness; submit on current SQL connection and return job UUID. |
58
+ | `queue.get(id)` | Owner-scoped summary/result or null; match client/user/grant and current target authorization. |
59
+
60
+ The context is bound to its original SQL/token scope. Reuse after that scope closes throws. Callback inheritance does not prolong scope lifetime. Read failures are not converted to apparent missing records. See [read maps](reads.md#return-maps).
61
+
62
+ ## Handler execution context
63
+
64
+ Job handlers receive input and can use SQL, log, a readonly execution token, job metadata, and the queue provider. There is no HTTP response or browser token-renewal lifecycle. `job` exposes `id?`, `path?`, `queue?`, `attempt?`, `source?`, `checking?`, and `reject(code)` through Server. The identity provider sees checking=true during startup preflight; actual attempts check authority again.
65
+
66
+ Successful null/false/scalar/array/map results are preserved. Controlled failures expose only code/permanent metadata. Automatic retries use the job's bounded retry settings; a permanent rejection skips them. [Execution contract](https://github.com/lango-project/lango-server/blob/master/docs/jobs.md).
67
+
68
+ ## Configuration and CLI
69
+
70
+ `routes.xml` job definitions require exact path, module, exported handler, and physical queue. They support Server group/include policy inheritance and stay out of HTTP routing. `deploy.xml` must configure PostgreSQL. `jobs.xml` is optional until a positive revision is deployed; subsequently clear schedules with a higher empty revision rather than removing the file.
71
+
72
+ ```sh
73
+ lango-boss check /path/to/app
74
+ lango-boss worker /path/to/app --identity-module @app/identity --identity-handler resolveExecutionIdentity --workers 2 --verbose
75
+ ```
76
+
77
+ `check` performs structural configuration validation only; it does not verify live identities or connect to the database. Worker reports startup/shutdown failure with nonzero status. No management HTTP/CLI application is installed by the core package; the reports example supplies its own local operator tool.
@@ -0,0 +1,103 @@
1
+ # Release preparation
2
+
3
+ This release pairs Lango Server **0.2.4** with Lango Boss **0.1.0**. Boss's manifest and lockfile require Server `^0.2.4`; the lock integrity is tied to the exact staged Server archive. Version 0.2.3 on the registry lacks required execution/database APIs and `Builder.loadDeployment()`.
4
+
5
+ The commands below prepare and test artifacts. They do not publish automatically.
6
+
7
+ ## 1. Prepare Server
8
+
9
+ From the sibling Server checkout, install development dependencies and run its checks:
10
+
11
+ ```sh
12
+ cd ../lango-server
13
+ npm ci --ignore-scripts
14
+ npm test
15
+ mkdir -p ../lango-boss/.test-output/release
16
+ npm pack --ignore-scripts --json --pack-destination ../lango-boss/.test-output/release
17
+ ```
18
+
19
+ The archive is `lango-project-lango-server-0.2.4.tgz`. Build before packing with `--ignore-scripts`; Server's `npm test` starts with its normal build.
20
+
21
+ ## 2. Stage Server in Boss
22
+
23
+ ```sh
24
+ cd ../lango-boss
25
+ npm run stage:server -- .test-output/release/lango-project-lango-server-0.2.4.tgz
26
+ ```
27
+
28
+ `stage:server` installs the local archive with install scripts disabled, then records its version, registry tarball URL, and exact SHA-512 integrity in Boss's manifest/lock. It does not leave a `file:` dependency or a global npm link. It uses the local npm cache; install/build Server's dependencies first. For a fresh Boss checkout with no compiler installed yet, first install that local Server tarball with `npm install --ignore-scripts /absolute/path/to/server.tgz`, then run `stage:server` to normalize the dependency back to the registry release.
29
+
30
+ If Server's packaged contents change, pack and stage it again. Do not reuse the old lock integrity for a different archive with the same version.
31
+
32
+ ## 3. Run source and package checks
33
+
34
+ Use an isolated PostgreSQL database where the test role may create schemas:
35
+
36
+ ```sh
37
+ npm test
38
+ LANGO_TEST_POSTGRES='postgresql://user@127.0.0.1/test_database' npm run test:postgres
39
+ LANGO_TEST_POSTGRES='postgresql://user@127.0.0.1/test_database' \
40
+ LANGO_TEST_SERVER_PACKAGE="$PWD/.test-output/release/lango-project-lango-server-0.2.4.tgz" \
41
+ npm run test:package
42
+ ```
43
+
44
+ Run build/test commands sequentially within the same package; its build cleans `dist/`.
45
+
46
+ The package test:
47
+
48
+ - Packs the current Boss build, documentation, and compiled reports application.
49
+ - Checks the Server archive against the committed lock integrity.
50
+ - Installs the real tarballs in a temporary directory outside the checkout, with only production dependencies and no install scripts.
51
+ - Runs a second clean production `npm ci --offline --omit=dev --ignore-scripts` against Boss's exact manifest/lock, using the staged cache.
52
+ - Verifies the production dependency tree does not contain the compiler and restricts runtime PATH so `lango` cannot be found.
53
+ - Copies only the example's compiled files/XML/package metadata, then runs setup, HTTP, the installed worker binary, and the operator CLI.
54
+ - Exercises automatic client registration, owner/foreign-client reads, scheduled `job_user`, retry with original client identity, queue/schedule pause/resume, queued cancel, audit, submission quota, and live client rejection.
55
+ - Checks graceful shutdown and removes only its own temporary directory and application schemas.
56
+
57
+ The test uses accelerated second-precision scheduling only in its isolated copy; the shipped example remains a one-minute schedule. The worker/operator run without the HTTP signing key. `npm ci` keeps a manifest/lock mismatch as an error and does not rewrite the lockfile. See the [npm ci documentation](https://docs.npmjs.com/cli/v11/commands/npm-ci/).
58
+
59
+ ## 4. Review the tested artifacts
60
+
61
+ The staging directory contains:
62
+
63
+ ```text
64
+ .test-output/release/
65
+ lango-project-lango-server-0.2.4.tgz
66
+ lango-project-lango-boss-0.1.0.tgz
67
+ release-manifest.json
68
+ ```
69
+
70
+ The manifest records archive paths and SHA-512 integrity values; `verified: true` is set after the full package flow succeeds. These are ignored local artifacts, not committed generated JavaScript. Review and commit the source/manifests/docs in their respective repositories. Changing Boss package contents afterward requires rerunning its package test before publication.
71
+
72
+ ## 5. Publish Server, then Boss
73
+
74
+ Publish the **tested tarballs** from the `lango-project` parent directory, rather than silently rebuilding a different artifact:
75
+
76
+ ```sh
77
+ npm publish lango-boss/.test-output/release/lango-project-lango-server-0.2.4.tgz --access public
78
+ npm view @lango-project/lango-server@0.2.4 dist.integrity
79
+ npm publish lango-boss/.test-output/release/lango-project-lango-boss-0.1.0.tgz --access public
80
+ ```
81
+
82
+ Compare the reported Server integrity with the release manifest/lock before publishing Boss. npm supports publishing tarball paths; see [npm publish](https://docs.npmjs.com/cli/v11/commands/npm-publish/). An already published name/version cannot be replaced with different contents; prepare a new version and update the dependency/lock if needed.
83
+
84
+ The offline package checks do not claim the new version is already available on the registry. After publication, verify a fresh registry installation separately:
85
+
86
+ ```sh
87
+ mkdir registry-check
88
+ cd registry-check
89
+ npm install --omit=dev --ignore-scripts @lango-project/lango-boss@0.1.0 @lango-project/lango-server@^0.2.4
90
+ npx --no-install lango-boss check /path/to/application
91
+ ```
92
+
93
+ ## Local use before publication
94
+
95
+ The same artifacts can be installed in a new application without publishing either package:
96
+
97
+ ```sh
98
+ npm install --omit=dev --ignore-scripts \
99
+ /absolute/path/to/lango-project-lango-server-0.2.4.tgz \
100
+ /absolute/path/to/lango-project-lango-boss-0.1.0.tgz
101
+ ```
102
+
103
+ Copy `node_modules/@lango-project/lango-boss/examples/reports` into a separate application directory and follow its README. Runtime installation needs neither npm linking nor the compiler. Third-party dependencies may be downloaded normally if they are not already cached.
@@ -0,0 +1,47 @@
1
+ # Retention cleanup
2
+
3
+ Worker enforces the version-1 envelope's `failedRetentionSeconds` for jobs in the terminal `failed` state. The default is seven days. Scheduled jobs may override it through `jobs.xml` defaults or individual job settings. The deadline starts at pg-boss's final `completed_on` failure timestamp, not submission time or the first failed attempt.
4
+
5
+ Created, retrying, and active jobs are never deleted by Boss retention cleanup. A manual retry that wins the row lock keeps the record; if cleanup has already deleted an expired record, a later retry cannot restore it. A later final failure starts a new retention period.
6
+
7
+ Completed and cancelled jobs retain the existing seven-day terminal storage policy, independent of `failedRetentionSeconds`. A terminal record with no completion timestamp is left intact. Missing, nonnumeric, fractional, zero, negative, or out-of-range failed-retention metadata uses the seven-day fallback so malformed records cannot break a sweep or request unlimited retention. Normal submissions validate metadata before execution.
8
+
9
+ ## Ownership and native retention
10
+
11
+ Cleanup only visits records in this application's hashed schema whose version and application name identify a Boss envelope. It leaves other applications and unrelated native records alone. It does not depend on the current route list: removing a route or schedule does not prevent its old terminal jobs from eventually expiring.
12
+
13
+ Boss submissions and schedule emission set native `deleteAfterSeconds` to zero. The native terminal cleanup therefore cannot remove a job earlier than its configured failed-retention deadline. Each Boss cleanup pass also protects existing matching records with nonzero native deletion settings before deleting expired records. Worker performs its first pass before enabling its own pg-boss supervision. Other, older supervisors should be drained during an upgrade; a deletion that committed before protection cannot be reversed.
14
+
15
+ Native `retentionSeconds`, which limits storage of waiting/retrying jobs, is unchanged. It is a separate pg-boss policy and is not a failed-job retention setting. Heartbeat and expiration supervision also remain active. See the [pg-boss retention options](https://pgboss.io/api/jobs#sendname-data-options).
16
+
17
+ ## Lifecycle and concurrency
18
+
19
+ A cleanup pass runs during Worker startup, then periodically while it is running. The standalone CLI uses the same Worker. No `jobs.xml` is required. A producer alone does not perform cleanup, so keep at least one Worker available for terminal records to expire.
20
+
21
+ ```lango
22
+ createWorker(directory)
23
+ return new boss/Worker(directory, {
24
+ identity: {
25
+ module: "@app/identity"
26
+ handler: "resolveExecutionIdentity"
27
+ }
28
+ cleanupIntervalSeconds: 60
29
+ cleanupBatchSize: 1000
30
+ })
31
+ ```
32
+
33
+ Each pass deletes at most `cleanupBatchSize` records, oldest completion first. One SQL statement selects and deletes candidates under row locks with `SKIP LOCKED`. Multiple replicas may sweep concurrently without deleting the same record twice or waiting on a row held by a concurrent retry. The schema adapter is tied to the pinned pg-boss version; its internal SQL is not an application API.
34
+
35
+ The batch bound limits deletions, not the number of rows examined or protected from native deletion. Large histories and long configured retention periods may require indexing or a dedicated retention worker in a later version. Native aggregate statistics can lag direct cleanup until their next refresh.
36
+
37
+ The next timer is armed after the previous pass finishes, so local passes never overlap. A full batch is followed by the normal delay, not an unbounded drain loop. Expiry is eventual: database downtime, all workers being stopped, locked rows, and large backlogs can postpone deletion. This is not an exact-time erasure guarantee.
38
+
39
+ Startup cleanup failure rejects Worker startup. Later failures are logged at error level and retried on the next periodic pass. Verbose mode reports how many terminal records were deleted without logging their payloads. Worker close cancels the timer and waits for an in-flight pass before releasing resources. Cleanup queries use the application's database timeout; this wait is separate from the handler shutdown grace period.
40
+
41
+ ## Tests
42
+
43
+ ```sh
44
+ LANGO_TEST_POSTGRES='postgresql://user@127.0.0.1/test_database' npm run test:retention
45
+ ```
46
+
47
+ The real PostgreSQL tests cover custom short/long failed lifetimes, independent successful/cancelled retention, live-state exclusion, malformed metadata, ownership, bounded concurrent deletion, retry locking, startup protection, periodic execution, and shutdown. They are also included in `test:postgres`.
@@ -0,0 +1,79 @@
1
+ # Scheduling
2
+
3
+ `Worker.start()` reconciles `jobs.xml` against the application's PostgreSQL schema before activating pg-boss cron. A producer does not activate schedules. The standalone worker command and embedded `Worker` use the same implementation.
4
+
5
+ ```xml
6
+ <jobs identity="job_user" revision="1" timeZone="UTC">
7
+ <defaults retryLimit="3" retryDelay="10" retryBackoff="true"
8
+ retryDelayMax="300" expireInSeconds="900"
9
+ failedRetentionSeconds="604800"/>
10
+ <job name="daily-report" path="/reports/create" cron="0 3 * * *"
11
+ timeZone="Europe/Istanbul" missed="once">
12
+ <data>{"reportType":"daily"}</data>
13
+ </job>
14
+ </jobs>
15
+ ```
16
+
17
+ The exact job path must be registered in `routes.xml`. Its module, handler, queue, policy, and authentication freshness come from that route. Schedule data is a JSON map and cannot override execution identity or choose a module. `<data>` accepts XML-escaped text or CDATA.
18
+
19
+ ## Definition fields
20
+
21
+ | Field | Default | Meaning |
22
+ | --- | --- | --- |
23
+ | Root `revision` | Required | Positive integer, at most 2147483647. Increase for each change to effective definitions. |
24
+ | Root `identity` | Required | Application-defined system profile shared by the file's jobs. |
25
+ | Root `timeZone` | `UTC` | Default IANA time zone. |
26
+ | Job `name` | Required | Unique stable schedule name within this application. |
27
+ | Job `path` | Required | Registered exact internal job path. |
28
+ | Job `cron` | Required | Valid cron expression. |
29
+ | Job `timeZone` | Root time zone | Per-job override. |
30
+ | Job `missed` | `skip` | `skip` or `once`; see downtime behavior below. |
31
+ | Job `precision` | `minute` | `minute` or `second`. Use `second` for schedules requiring every-second evaluation. |
32
+ | Job `enabled` | `true` | Disabled jobs remain defined but have no active native schedule. |
33
+
34
+ Retry/expiration/failed-retention fields may appear in `<defaults>` or on a job. Per-job values override defaults regardless of XML ordering. `retryLimit` may be zero; delay values and expiration must be positive integers, and `retryDelay` cannot exceed `retryDelayMax`. Expiration is at most 1209600 seconds. Worker [retention cleanup](retention.md) enforces each job's `failedRetentionSeconds` from its final failure timestamp.
35
+
36
+ ## Revision and deployment rules
37
+
38
+ Reconciliation acquires an application-specific PostgreSQL transaction advisory lock. Revision checks, native schedule changes, and the ownership registry commit together. A failure rolls the entire reconciliation back.
39
+
40
+ - A higher revision installs the new definitions.
41
+ - The same revision with the same effective definitions is accepted. Object-key and job declaration ordering do not change the fingerprint. Restarting preserves pg-boss's occurrence cursor for unchanged cron, time zone, and precision.
42
+ - The same revision with different effective definitions fails startup.
43
+ - A lower revision fails startup and cannot restore older definitions.
44
+
45
+ The fingerprint includes normalized defaults, input data, system identity, enabled state, retry settings, and resolved queue assignments. Changing a route's queue therefore requires a schedule revision increase even if the text of `jobs.xml` stays the same. Handler code and permission changes are not schedule fingerprints; the live authorization rules still apply at execution.
46
+
47
+ An application with no `jobs.xml` initially uses revision zero and starts without cron. After any positive revision has been deployed, removing the file fails startup rather than silently removing schedules. To remove all schedules, deploy a higher revision with no jobs:
48
+
49
+ ```xml
50
+ <jobs identity="job_user" revision="2"/>
51
+ ```
52
+
53
+ For a rollback, publish the older desired definitions under a **new higher revision**. Do not decrement the revision. Keep the application's package name stable: it defines its database namespace.
54
+
55
+ Multiple replicas share database claims and occurrence cursors. A replica already running continues to read the current native schedule table; it does not periodically rewrite its startup XML. A newly starting replica carrying an older revision fails. During rolling deployment, keep old and new worker routes/handlers compatible until the old workers are drained: revision fencing protects schedule configuration, not the application code executing an already queued job.
56
+
57
+ ## Ownership and pause state
58
+
59
+ Application and schedule names map to stable hashed pg-boss keys, so scoped npm names and human-readable schedule names work without adopting native key character restrictions. The registry keeps the original name and owning queue/key. Removing or moving a definition only removes its previously owned native schedule. It never deletes already queued jobs or unrelated native schedules. A new definition colliding with an unowned native key is rejected atomically.
60
+
61
+ The registry retains removed definitions as tombstones and preserves its operational `paused` flag across reconciliation, restarts, and removal/reintroduction. A paused job or `enabled="false"` has no native schedule. Enabling XML does not override an operational pause. Use the authorized [pauseSchedule/resumeSchedule management functions](management.md#schedule-pause-and-resume); direct edits to internal tables are not a supported application API.
62
+
63
+ ## Authorization and downtime
64
+
65
+ Before cron is activated, Worker calls `Executor.authorize()` for each distinct system identity/target pair, including disabled definitions. This resolves the profile and checks its current policy/freshness without calling the job handler. Unknown or unauthorized profiles fail startup. The identity provider receives a preflight job context with `checking? == true`; it should not treat preflight as an executed job or grant different permissions. Every actual attempt resolves live authority again.
66
+
67
+ pg-boss owns cron leases, occurrence cursors, and concurrent schedule emission. `missed="skip"` does not replay occurrences missed during an uncovered gap. `missed="once"` emits at most one catch-up job for the latest applicable missed occurrence, rather than replaying every occurrence. Catch-up data is the configured map, not a generated history of occurrence timestamps. Normal due-window evaluation is still performed by pg-boss.
68
+
69
+ Schedules are not hard real-time timers. Minute schedules use the shared scan interval; second schedules use pg-boss's second tick within the scan lease. Native caches and in-flight scans mean a change or removal can overlap a previously read definition until that lease expires. Reconciliation does not cancel such emissions or already queued/running work. Handler effects still need idempotency, and successful application commits remain separate from queue completion.
70
+
71
+ See the [worker guide](worker.md) for `cronMonitorIntervalSeconds`, shutdown, and execution limits, and the [pg-boss scheduling API](https://pgboss.io/api/scheduling) for the underlying scheduling behavior.
72
+
73
+ ## Verification
74
+
75
+ ```sh
76
+ LANGO_TEST_POSTGRES='postgresql://user@127.0.0.1/test_database' npm run test:schedules
77
+ ```
78
+
79
+ The real PostgreSQL suite checks mapping, stable cursors, revision fencing, atomic rollback, ownership, empty-file removal rules, persistent pause state, concurrent reconciliation, system-profile preflight, actual scheduled execution, and controlled-clock downtime behavior. `test:postgres` also includes the producer and consumer suites. Use an isolated test database.
package/docs/worker.md ADDED
@@ -0,0 +1,90 @@
1
+ # Worker execution
2
+
3
+ `Worker` consumes registered job queues and invokes their handlers through Lango Server's HTTP-free Executor. It uses the same application directory, `deploy.xml`, `routes.xml`, and application name as the producer. It never starts an HTTP listener.
4
+
5
+ Worker configuration readers do not resolve HTTP JWT secrets or signing-key files. A worker can therefore use the application's deployment file without receiving the HTTP signing credentials.
6
+
7
+ ## Embedded consumer
8
+
9
+ ```lango
10
+ import js "@lango-project/lango-boss" as boss
11
+
12
+ createWorker(directory)
13
+ return new boss/Worker(directory, {
14
+ identity: {
15
+ module: "@app/identity"
16
+ handler: "resolveExecutionIdentity"
17
+ }
18
+ workers: 2
19
+ pollingIntervalSeconds: 2
20
+ startupTimeoutMs: 30000
21
+ shutdownTimeoutMs: 30000
22
+ })
23
+ ```
24
+
25
+ Call `start()` and retain the instance for `close()`; both return Promises. A second start is rejected and close is idempotent. The identity provider is mandatory and uses the [Server execution identity contract](https://github.com/lango-project/lango-server/blob/master/docs/jobs.md). It must resolve live application authorization on every attempt, including current bans, revoked grants, policies, and real authentication freshness. A missing provider export fails startup before any work is claimed.
26
+
27
+ Return `authenticatedAt`, when present, as a safe integer millisecond number. Convert the database representation deliberately; do not replace the actual authentication time with the current time.
28
+
29
+ | Setting | Default | Meaning |
30
+ | --- | --- | --- |
31
+ | `identity` | Required | Application module and exported identity resolver. |
32
+ | `workers` | 2 | Executor threads, from 1 to 128; also polling concurrency per queue. |
33
+ | `pollingIntervalSeconds` | 2 | Poll interval; from 0.5 to 3600 seconds. |
34
+ | `heartbeatRefreshSeconds` | Automatic | Normally half the claimed job's heartbeat interval. An explicit value must be shorter than every consumed job's heartbeat; supported range is 0.5–29 seconds. |
35
+ | `cronMonitorIntervalSeconds` | 30 | Shared cron scan/lease interval, from 1 to 45 seconds. Second-precision schedules use pg-boss's second tick under that lease. |
36
+ | `cleanupIntervalSeconds` | 60 | Delay after a retention pass before starting another; from 1 to 86400 seconds. |
37
+ | `cleanupBatchSize` | 1000 | Maximum terminal records deleted per pass, from 1 to 10000. |
38
+ | `startupTimeoutMs` | 30000 | Executor startup deadline. Database operations also use configured database timeouts. |
39
+ | `shutdownTimeoutMs` | 30000 | Local execution shutdown grace period and subsequent pg-boss settlement drain bound. |
40
+
41
+ There is one dispatcher registration per queue, shared by all of that queue's paths. A polling registration can have several local lanes. The shared Executor limits simultaneous application execution to `workers`; the local waiting capacity is derived from the number of queues and lanes. A job's lease includes time spent waiting locally, so avoid registering very large numbers of busy queues on a small executor.
42
+
43
+ The worker's control-plane pool has four connections, separate from application SQL connections. The producer keeps its two-connection pool and never starts consumers implicitly. Startup uses a temporary producer driver to prepare queues and reconcile configuration. A retention pass protects Boss records from native terminal expiry before the consumer driver activates supervision and instance registration. When `jobs.xml` is present, cron also activates after system identity checks and reconciliation. See [scheduling](scheduling.md) and [retention cleanup](retention.md). Reconciliation and each cleanup pass use a temporary application SQL scope, closed when that operation finishes; no permanent extra cleanup pool is kept.
44
+
45
+ ## Standalone process
46
+
47
+ ```sh
48
+ lango-boss worker /path/to/application \
49
+ --identity-module @app/identity \
50
+ --identity-handler resolveExecutionIdentity \
51
+ --workers 2
52
+ ```
53
+
54
+ Use `--verbose` for the standard verbose logging mode. The identity module resolves from the application directory. Invalid options and startup failures exit with status 1. SIGINT/SIGTERM stop fetching, close execution, drain settlement, and release database resources. Failed shutdown sets a nonzero exit status. Only the CLI's own signal listeners are removed.
55
+
56
+ The CLI uses the same Worker implementation as embedded consumption. `lango-boss check <directory>` remains a configuration-only check and does not start a worker or verify live user permissions.
57
+
58
+ ## Dispatch and authorization
59
+
60
+ A claimed record must carry a version-1 envelope for this application, a path registered on the physical queue that supplied it, a JSON-map input, and structurally valid source references. Unknown envelope fields, foreign application names, missing paths, or mixed user/system sources fail permanently before application code is invoked. Module and handler names always come from current route configuration.
61
+
62
+ The executor receives the actual job ID and `retryCount + 1` as the attempt number. It resolves live identity before calling the handler. No browser JWT is reconstructed or extended, and input fields cannot grant permissions or select a system profile. Multiple worker processes use the same database claims; there is no process-local authority cache.
63
+
64
+ Job timeout comes from the claimed pg-boss expiration metadata. The Executor receives the native AbortSignal combined with a local claim watcher's signal. The watcher checks the fetched attempt with pg-boss's fenced `touch()` about once per second, including jobs without a native heartbeat interval. Detected cancellation or claim loss aborts waiting/running execution and terminates blocking local code. New submissions also carry a 30-second native heartbeat. A failed database check is logged and does not imply loss of authority; expiration remains independently bounded. See [active cancellation](management.md#active-cancellation) for timing and side-effect limits.
65
+
66
+ ## Outcomes
67
+
68
+ Workers use pg-boss per-job dispositions, with the fetched attempt retained for fenced settlement:
69
+
70
+ - Successful output completes the claimed attempt.
71
+ - Ordinary handler/provider failures, worker crashes, or interrupted execution enter the job's configured bounded retry policy.
72
+ - `job.reject(code)`, identity rejection, identity mismatch, missing permission, stale authentication, and invalid envelopes fail terminally without consuming the remaining automatic retries.
73
+
74
+ Terminal disposition uses pg-boss's `deadletter` result internally. With the standard queues created here and no dead-letter destination configured, the original job simply ends in `failed`; no separate dead-letter application queue is required.
75
+
76
+ Success is stored as an internal `{ version: 1, value: output }` envelope, preserving null, false, scalars, arrays, and maps without confusing them with missing output. Controlled failure output contains `{ version: 1, error: { code, permanent } }`; application input, tokens, and stack traces are not copied into that failure record. Native infrastructure failures can still be recorded by pg-boss itself. Public [status/result reads](reads.md) expose recognized results and controlled error codes without exposing native messages or stacks.
77
+
78
+ Per-job completion and failure carry the claimed retry count. If an earlier handler returns after its job was reclaimed, its disposition cannot complete or fail the newer active attempt. The Executor additionally responds to claim-loss cancellation to stop further local work where possible. This does not reverse side effects already committed.
79
+
80
+ ## Transactions and shutdown
81
+
82
+ Application SQL commits and pg-boss completion are separate transactions in this implementation. An unclosed handler transaction is rolled back and rejected. An explicit application commit is durable even if the process dies before completion is recorded. Such a job can execute again: use the job ID or an application operation key to make effects idempotent. There is no exactly-once guarantee.
83
+
84
+ Shutdown first stops new queue fetches. Accepted local executions get the configured grace period; a deadline terminates the remaining worker threads and reports failure. The control-plane connection stays open while handlers' outcomes settle, and closes afterward. Interrupted execution is never completed as a success. A hard process or machine failure is recovered through pg-boss expiration/heartbeat supervision while another supervisor is available.
85
+
86
+ ## Current limits
87
+
88
+ Management operations are available through the package's authorized [management API](management.md). Retention cleanup works independently of schedule configuration and stops with the Worker. Full process/node loss and network-partition fault injection, workload/index measurements, and release packaging remain separate validation work.
89
+
90
+ For the underlying settlement and heartbeat contracts, see the [pg-boss worker API](https://pgboss.io/api/workers).