gowalk-cicd 1.0.216 → 1.0.218

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.
package/README.md CHANGED
@@ -1266,8 +1266,22 @@ A failed upload emits the typed `apple_build_upload_failed` error annotation wit
1266
1266
  `processing_pending`, or a fallback such as `local_io`), `stage`, `receipt_available` and
1267
1267
  the receipt's own identifiers (`cfBundleVersion`, `upload_id`, `file_id`, `state`,
1268
1268
  `provider_status`, `provider_code`, `provider_pointer`). Exception text is never
1269
- published. The job also retains the exact exported IPA as `apple-ipa-<run>-<attempt>`
1270
- (7 days), copied without byte changes to the safe archive member `app.ipa`, so punctuation
1269
+ published. From 1.0.218 a failed App Store Connect request publishes its final HTTP status as
1270
+ `provider_status`, including unclassified 429/5xx responses; a request that received no response
1271
+ records only the closed `network_error` label in the retained receipt (the annotation shape is unchanged) (`tls`, `connect_timeout`, `read_timeout`, `timeout`,
1272
+ `connection` or `request`). Reads and the `uploaded: true` commit of the one reserved file make
1273
+ up to three attempts on 429, 500, 502, 503, 504 or a network error (2 s, then 8 s backoff);
1274
+ creates and classified refusals (400, 401, 403, 404, 409, 412, 422) are never repeated.
1275
+ `provider_request_failed` at stage `file_reserved` means every part transferred and only the
1276
+ commit failed. Read that receipt's `file_id` back first with the account-pinned store tooling: while it
1277
+ is still `AWAITING_UPLOAD`, that same tooling may send the same `uploaded: true` body once (never a
1278
+ direct Mac call or another upload), then read the file back `COMPLETE` with any nonnull whole-file
1279
+ checksum matching the retained IPA and the unique matching build before treating it as delivered, and
1280
+ reconcile the deployment as described above.
1281
+ Never upload different bytes under the same build number.
1282
+
1283
+ The job also retains the exact exported IPA as `apple-ipa-<run>-<attempt>` (7 days),
1284
+ copied without byte changes to the safe archive member `app.ipa`, so punctuation
1271
1285
  in the exported filename cannot block retention. A continuation can complete that upload instead of rebuilding
1272
1286
  different bytes under the same number. Build numbers come from `/builds`,
1273
1287
  `/preReleaseVersions` **and** `/apps/{id}/buildUploads`, so an unfinished or refused
@@ -1410,7 +1424,10 @@ Each invocation uses a fresh local directory so a failed reader cannot publish a
1410
1424
 
1411
1425
  The backend action's `operation: runtime-diagnostics` reads the exact app project and expected deployed SHA,
1412
1426
  returning actual service count, effective limits, two bounded resource samples and private database-binding
1413
- provenance. Call it from the app's read-only diagnostic workflow with `diagnostic-service` and
1427
+ provenance. From 1.0.217 it also requests current-container restart count, OOM flag, start/finish timestamps
1428
+ and health status; install the published host runtime before adopting that client. A refused or missing
1429
+ observation stays unavailable, never a zero count or evidence that no historical restart occurred.
1430
+ Call it from the app's read-only diagnostic workflow with `diagnostic-service` and
1414
1431
  `expected-build-sha`, using its existing host/key/pin inputs. It requires the released host forced command as well
1415
1432
  as the updated action. See [the scoped runtime contract and host installer](docs/BACKEND_SSH_GATE.md#applied-runtime-readback).
1416
1433
  Identity failure logs and source Compose files do not establish this applied state.
@@ -165,6 +165,17 @@ def _request_timeouts() -> tuple[float, float]:
165
165
  )
166
166
 
167
167
 
168
+ class RequestFailed(SystemExit):
169
+ """Terminal ``request`` failure. It stays a SystemExit with the same message, so
170
+ existing callers are unchanged; ``status`` (HTTP) or ``category`` (closed network
171
+ label) lets a caller publish the cause without the message's provider text."""
172
+
173
+ def __init__(self, message: str, *, status: int | None = None, category: str = ""):
174
+ super().__init__(message)
175
+ self.status = status
176
+ self.category = category
177
+
178
+
168
179
  def _network_error_category(exc: BaseException) -> str:
169
180
  """Closed diagnostic labels only; exception text can contain private URLs."""
170
181
  for error_type, category in (
@@ -184,12 +195,12 @@ def _retry_network_error(
184
195
  backoffs: tuple[int, ...], exc: BaseException,
185
196
  ) -> None:
186
197
  """Network error path: sleep and return when retries remain, else
187
- raise SystemExit (terminal). Caller ``continue``s after return."""
198
+ raise RequestFailed (terminal). Caller ``continue``s after return."""
188
199
  category = _network_error_category(exc)
189
200
  if attempt >= total - 1:
190
- raise SystemExit(
201
+ raise RequestFailed(
191
202
  f"ASC {method} {path} network error after {total} "
192
- f"attempts (category={category})"
203
+ f"attempts (category={category})", category=category,
193
204
  )
194
205
  delay = backoffs[attempt]
195
206
  print(
@@ -235,7 +246,7 @@ def request(
235
246
  raising (useful for 409 conflict handling). Per-request timeouts come
236
247
  from ``_request_timeouts()`` (env-overridable); without them a hung
237
248
  TCP socket would block the CI runner indefinitely.
238
- Raises SystemExit on non-retryable failure with a clear stderr message.
249
+ Raises RequestFailed (a SystemExit) on non-retryable failure with a clear message.
239
250
  """
240
251
  url = f"{ASC_BASE}{path}"
241
252
  headers = {"Authorization": f"Bearer {token}"}
@@ -263,8 +274,9 @@ def request(
263
274
  continue
264
275
  break
265
276
  assert resp is not None
266
- raise SystemExit(
267
- f"ASC {method} {path} failed: {resp.status_code}\n{resp.text[:2000]}"
277
+ raise RequestFailed(
278
+ f"ASC {method} {path} failed: {resp.status_code}\n{resp.text[:2000]}",
279
+ status=resp.status_code,
268
280
  )
269
281
 
270
282
 
@@ -26,13 +26,20 @@ from upload_receipt import Receipt, UploadError
26
26
  CLASSIFIED_STATUSES = {400, 401, 403, 404, 409, 412, 422}
27
27
 
28
28
 
29
- def api(method: str, path: str, body=None, params=None) -> dict:
29
+ def api(method: str, path: str, body=None, params=None, *, idempotent: bool = False) -> dict:
30
30
  token = asc_common.make_jwt(os.environ["ASC_KEY_ID"], os.environ["ASC_ISSUER_ID"],
31
31
  os.environ["ASC_KEY_PATH"])
32
- # An uncertain create is discovered from the provider on the next invocation,
33
- # never repeated automatically under a second upload identity.
34
- response = asc_common.request(method, path, token, json_body=body, params=params,
35
- allow_status=CLASSIFIED_STATUSES, max_attempts=3 if method == "GET" else 1)
32
+ # Reads and the idempotent uploaded=true commit retry 429/5xx/network failures. An
33
+ # uncertain create is discovered from the provider on the next invocation, never
34
+ # repeated automatically under a second upload identity.
35
+ try:
36
+ response = asc_common.request(method, path, token, json_body=body, params=params,
37
+ allow_status=CLASSIFIED_STATUSES,
38
+ max_attempts=3 if method == "GET" or idempotent else 1)
39
+ except asc_common.RequestFailed as exc:
40
+ # Only the HTTP status or the closed network label is published, never the message.
41
+ cause = {"provider_status": exc.status} if exc.status else {"network_error": exc.category}
42
+ raise UploadError("provider_request_failed", f"Apple request {method} {path} failed", **cause) from None
36
43
  if response.status_code >= 400:
37
44
  try:
38
45
  error = (response.json().get("errors") or [{}])[0]
@@ -152,7 +159,7 @@ def transfer_all(ipa: Path, file: dict, info: dict) -> None:
152
159
  # checksum enum includes SHA_256, but IPA finalization rejected that
153
160
  # optional attribute with ENTITY_ERROR.ATTRIBUTE.INVALID in production.
154
161
  "type": "buildUploadFiles", "id": file["id"], "attributes": {"uploaded": True},
155
- }})
162
+ }}, idempotent=True)
156
163
 
157
164
 
158
165
  def deliver(ipa: Path, report: Path, timeout: int, handoff: Path | None = None) -> dict:
@@ -34,7 +34,8 @@ def local(args, transport=None):
34
34
  if (not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9.-]{0,252}', args.host or '')
35
35
  or not re.fullmatch(r'[a-z_][a-z0-9_-]{0,31}', args.user)):
36
36
  raise RuntimeFailure('invalid_scope')
37
- command = shlex.join(['gowalk-backend', 'runtime-diagnostics', args.app, args.service, args.expected_build_sha])
37
+ command = shlex.join(['gowalk-backend', 'runtime-diagnostics', args.app, args.service,
38
+ args.expected_build_sha, 'lifecycle'])
38
39
  try:
39
40
  status, raw, errors = bounded(['ssh', '-T', '-i', str(Path.home() / '.ssh/backend_deploy'),
40
41
  '-o', 'IdentitiesOnly=yes', '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=yes',
@@ -57,6 +58,8 @@ def local(args, transport=None):
57
58
  raise RuntimeFailure('remote_invalid') from None
58
59
  if result['ok'] != (status == 0):
59
60
  raise RuntimeFailure('remote_invalid')
61
+ if result['ok'] and any('lifecycle' not in row for row in result['services']):
62
+ raise RuntimeFailure('remote_invalid')
60
63
  return result
61
64
 
62
65
 
@@ -1,4 +1,5 @@
1
1
  """Closed, credential-free envelope for one app's deployed runtime observations."""
2
+ import datetime
2
3
  import math
3
4
  import re
4
5
 
@@ -34,10 +35,31 @@ def number(value, *, integer=False, positive=False):
34
35
  raise RuntimeFailure('remote_invalid')
35
36
 
36
37
 
38
+ def lifecycle_record(row):
39
+ fields = {'restart_count', 'oom_killed', 'started_at', 'finished_at', 'health_status'}
40
+ if not isinstance(row, dict) or set(row) != fields:
41
+ raise RuntimeFailure('remote_invalid')
42
+ if (type(row['restart_count']) is not int or not 0 <= row['restart_count'] <= 2 ** 53 - 1
43
+ or type(row['oom_killed']) is not bool or not isinstance(row['health_status'], str)
44
+ or row['health_status'] not in {'none', 'starting', 'healthy', 'unhealthy'}):
45
+ raise RuntimeFailure('remote_invalid')
46
+ for name in ('started_at', 'finished_at'):
47
+ value = row[name]
48
+ if (not isinstance(value, str) or len(value) > 30
49
+ or not re.fullmatch(r'\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,9})?Z', value)):
50
+ raise RuntimeFailure('remote_invalid')
51
+ try:
52
+ datetime.datetime.strptime(value[:19], '%Y-%m-%dT%H:%M:%S')
53
+ except ValueError:
54
+ raise RuntimeFailure('remote_invalid') from None
55
+
56
+
37
57
  def service_record(row):
38
58
  fields = {'service', 'container_id', 'image_id', 'running', 'limits', 'samples'}
39
- if not isinstance(row, dict) or set(row) != fields:
59
+ if not isinstance(row, dict) or set(row) not in (fields, fields | {'lifecycle'}):
40
60
  raise RuntimeFailure('remote_invalid')
61
+ if 'lifecycle' in row:
62
+ lifecycle_record(row['lifecycle'])
41
63
  for name, pattern in (('service', SERVICE), ('container_id', CID), ('image_id', 'sha256:' + CID)):
42
64
  if not isinstance(row[name], str) or not re.fullmatch(pattern, row[name]):
43
65
  raise RuntimeFailure('remote_invalid')
@@ -14,6 +14,9 @@ APPS = Path('/opt/gowalk-backends')
14
14
  PROFILES = Path('/opt/gowalk-backend-runtime')
15
15
  ROOT_UID = 0
16
16
  INSPECT = ('{"id":{{json .Id}},"image":{{json .Image}},"running":{{json .State.Running}},'
17
+ '"lifecycle":{"restart_count":{{json .RestartCount}},"oom_killed":{{json .State.OOMKilled}},'
18
+ '"started_at":{{json .State.StartedAt}},"finished_at":{{json .State.FinishedAt}},'
19
+ '"health_status":{{if .State.Health}}{{json .State.Health.Status}}{{else}}"none"{{end}}},'
17
20
  '"project":{{json (index .Config.Labels "com.docker.compose.project")}},'
18
21
  '"service":{{json (index .Config.Labels "com.docker.compose.service")}},'
19
22
  '"directory":{{json (index .Config.Labels "com.docker.compose.project.working_dir")}},'
@@ -119,16 +122,19 @@ def usage(rows):
119
122
  return result
120
123
 
121
124
 
122
- def public_row(row, samples):
125
+ def public_row(row, samples, lifecycle=False):
123
126
  cpus = row['nano_cpus'] / 1e9 if row['nano_cpus'] else (
124
127
  row['quota'] / row['period'] if row['quota'] > 0 and row['period'] > 0 else 0)
125
- return {'service': row['service'], 'container_id': row['id'], 'image_id': row['image'],
128
+ result = {'service': row['service'], 'container_id': row['id'], 'image_id': row['image'],
126
129
  'running': row['running'], 'limits': {'memory_bytes': row['memory'],
127
130
  'reservation_bytes': row['reservation'], 'cpu_limit': cpus, 'pids_limit': row['pids']},
128
131
  'samples': [sample[row['id']] for sample in samples] if row['running'] else []}
132
+ if lifecycle:
133
+ result['lifecycle'] = row['lifecycle']
134
+ return result
129
135
 
130
136
 
131
- def collect(app, service, expected):
137
+ def collect(app, service, expected, lifecycle=False):
132
138
  scope(app, service, expected)
133
139
  original_profile = profile(app)
134
140
  identifiers = containers(app)
@@ -143,7 +149,7 @@ def collect(app, service, expected):
143
149
  if profile(app) != original_profile:
144
150
  raise RuntimeFailure('profile_changed')
145
151
  result = dict(envelope(app, service, expected), observed_build_sha=expected,
146
- services=[public_row(row, samples) for row in rows], container_count=len(rows),
152
+ services=[public_row(row, samples, lifecycle) for row in rows], container_count=len(rows),
147
153
  database=binding,
148
154
  observed_at=datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ'))
149
155
  return validate(result, app, service, expected)
@@ -152,7 +158,9 @@ def collect(app, service, expected):
152
158
  def main():
153
159
  app, service, expected = (sys.argv[1:] + ['', '', ''])[:3]
154
160
  try:
155
- result = collect(app, service, expected)
161
+ if len(sys.argv) not in (4, 5) or len(sys.argv) == 5 and sys.argv[4] != 'lifecycle':
162
+ raise RuntimeFailure('invalid_scope')
163
+ result = collect(app, service, expected, len(sys.argv) == 5)
156
164
  except Exception as error:
157
165
  result = envelope(app, service, expected, error.code if isinstance(error, RuntimeFailure) else 'unclassified')
158
166
  print(json.dumps(result, separators=(',', ':')))
@@ -82,10 +82,12 @@ def authorize(owner, project, policy, may_claim):
82
82
  def helper_command(words):
83
83
  if words[:2] == ['gowalk-backend', 'network-diagnostics']:
84
84
  return network_command(words)
85
- if len(words) == 5 and words[:2] == ['gowalk-backend', 'runtime-diagnostics']:
85
+ if len(words) in (5, 6) and words[:2] == ['gowalk-backend', 'runtime-diagnostics']:
86
86
  from runtime_projection import RuntimeFailure, scope
87
87
  try:
88
- scope(*words[2:])
88
+ scope(*words[2:5])
89
+ if len(words) == 6 and words[5] != 'lifecycle':
90
+ raise RuntimeFailure('invalid_scope')
89
91
  except RuntimeFailure:
90
92
  raise ValueError('ssh_arguments_refused') from None
91
93
  return words[2], False, [sys.executable, str(HELPERS / 'runtime_readback.py'), *words[2:]]
@@ -62,7 +62,9 @@ Failures emit only `backend_ssh_refused`, never the original command or private
62
62
 
63
63
  The released backend action accepts `operation: runtime-diagnostics`, `diagnostic-service` (default `api`) and
64
64
  `expected-build-sha`. Its existing pinned CI SSH identity issues only
65
- `gowalk-backend runtime-diagnostics <project> <service> <40-character-SHA>`. The forced command checks the same
65
+ `gowalk-backend runtime-diagnostics <project> <service> <40-character-SHA> lifecycle` from version 1.0.217.
66
+ The optional final token selects lifecycle observations; older clients omit it and receive the original shape.
67
+ The forced command checks the same
66
68
  panel/project ownership and global freeze, then executes its own released `runtime_readback.py`. It never runs
67
69
  consumer code or an uploaded script. An older/refusing gate has no reader receipt and the client returns
68
70
  `runtime_reader_unavailable`; locally synthesized failures carry `reader_version: null`, never host-adoption proof.
@@ -77,6 +79,26 @@ Docker's display precision. CPU samples are Docker's bounded observations, not a
77
79
  collector never launches workload, reads logs, executes in containers or inspects a shared database's cgroup.
78
80
  Both container identity/configuration and the private profile are rechecked before returning success.
79
81
 
82
+ The opted-in response adds a closed `lifecycle` object to each service:
83
+
84
+ - `restart_count`: Docker's nonnegative restart count for that exact container, bounded to a safe JSON integer;
85
+ - `oom_killed`: Docker's boolean OOM observation for its current recorded state;
86
+ - `started_at` and `finished_at`: Docker UTC timestamps, with at most nine fractional digits;
87
+ - `health_status`: `none`, `starting`, `healthy` or `unhealthy`; `none` means no Docker healthcheck is present.
88
+
89
+ The Docker zero timestamp `0001-01-01T00:00:00Z` is retained as reported. No exit error, healthcheck command,
90
+ health log or raw state object is read or returned. The same container's lifecycle changing between resource
91
+ samples and the final inspect refuses `runtime_changed`, rather than joining observations across a restart.
92
+ These facts do not establish the cause of an HTTP 502. Zero restarts or `oom_killed: false` cannot exclude
93
+ earlier OOM/restarts on a replaced container; compare exact container IDs and separately observed app behavior.
94
+
95
+ Install the integrity-verified 1.0.217 host runtime through `install_runtime.py` below before adopting the new
96
+ client. New clients require the requested lifecycle fields; old hosts that refuse the fixed token produce
97
+ `runtime_reader_unavailable` with the existing transport observations, never invented lifecycle defaults or
98
+ automatic unrestricted recovery. The v1 schema and reader marker stay compatible; the install receipt and
99
+ forced-command release path prove host adoption. A new host still serves old clients the unchanged v1 response
100
+ when they omit the token. Read-only diagnostics never install or update the host helper themselves.
101
+
80
102
  The same artifact also retains `transport.json`, schema `gowalk-cicd/backend-runtime-transport.v1`.
81
103
  Its fixed fields also appear in the brace-free `backend_runtime_transport` notice. It reports the SSH child's
82
104
  `exit_status` (null when no complete exit was observed) and fixed `signals`: `gate_refused`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gowalk-cicd",
3
- "version": "1.0.216",
3
+ "version": "1.0.218",
4
4
  "description": "Zero-config GitHub Actions delivery for iOS TestFlight and Android Google Play.",
5
5
  "type": "module",
6
6
  "bin": {
package/remedies.json CHANGED
@@ -5,6 +5,12 @@
5
5
  "fixed_in": "1.0.216",
6
6
  "remedy": "Keep the original IPA and apple-build-upload receipt. From 1.0.216 default-branch Linux candidate promotion retains the same authenticated verification handoff as macOS delivery; adopt the action and generated workflow together. Earlier inline Linux processing_pending failures have no handoff: do not fabricate one or use the handoff-only recovery workflow. In an authorized same-repository default-branch Actions job, authenticate the original apple-upload-<run>-<attempt> artifact and archive digest, then run reconcile_apple_upload.cjs DEPLOYMENT_ID ORIGINAL_RUN_ID ORIGINAL_ATTEMPT /path/to/apple-build-upload.json with that unchanged receipt. Serialize with Mobile Deploy and preserve its original owner. The released helper requires fresh completed upload/file/checksum and unique VALID eligible iOS build/app proof; it never rebuilds or uploads. Retain its result, read back uploaded, then rerun the whole original deploy. Missing original bytes or checksum proof remain unverified; never invent digests, upload another binary under the same number or hand-edit ownership."
7
7
  },
8
+ {
9
+ "schema": "gowalk-cicd/apple-build-upload-failed.v2",
10
+ "code": "provider_request_failed",
11
+ "fixed_in": "1.0.218",
12
+ "remedy": "Keep the original IPA artifact, apple-build-upload receipt and deployment owner. From 1.0.218 the uploaded=true commit of the one reserved file retries 429, 500, 502, 503, 504 and network errors up to three attempts, like reads; creates and classified refusals still run once. A failed request publishes its HTTP status as provider_status; when no response arrived the receipt keeps only the closed network_error label. Exception text, URLs and provider bodies stay private. Stage file_reserved means every part transferred and only the commit failed. Read that file_id back with the account-pinned store tooling; while it is still AWAITING_UPLOAD, that tooling may send the same uploaded=true body once (never a direct Mac call or another upload). Then read the file back COMPLETE with any nonnull whole-file checksum matching the retained IPA and the unique matching build, and reconcile the named deployment to success/uploaded with that evidence. Do not fabricate a handoff or relabel the receipt, and never upload different bytes under the same build number."
13
+ },
8
14
  {
9
15
  "schema": "gowalk-cicd/mobile-release-refused.v1",
10
16
  "code": "mobile_release_phase_owner_mismatch",