@ocap/tx-protocols 1.30.10 → 1.30.11

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/esm/execute.mjs CHANGED
@@ -25,7 +25,9 @@ const getStates = (context) => {
25
25
  return context.states;
26
26
  };
27
27
  const flushEvents = (context, extra = {}) => {
28
- (context.events || []).forEach((e) => {
28
+ const events = context.events || [];
29
+ if (events.length) context.timer?.incrCounter("indexEvents", events.length);
30
+ events.forEach((e) => {
29
31
  const table = context.statedb[e.table];
30
32
  if (table?.emit) table.emit(e.name, e.data, {
31
33
  ...e.ctx,
@@ -116,6 +118,7 @@ const createExecute = ({ filter, runAsLambda }) => {
116
118
  txState = states.tx.create(context, txStatus);
117
119
  }
118
120
  await context.statedb.tx.create(txState.hash, txState, context);
121
+ context.timer?.mark("txstate");
119
122
  context.timer?.mark("commit");
120
123
  flushEvents(context, { txState });
121
124
  context.timer?.mark("indexdb");
@@ -128,12 +131,23 @@ const createExecute = ({ filter, runAsLambda }) => {
128
131
  });
129
132
  return reject(error);
130
133
  }
134
+ context.timer?.setMeta({
135
+ txType: context.txType,
136
+ txSize: context.txSize,
137
+ senderAddr: context.tx?.from,
138
+ ledgerSequence: context.ledgerSequence,
139
+ status: error ? shouldPersistTx(error) ? "PERSISTED_FAILED" : "FAILED" : "OK",
140
+ errorCode: error ? error.code || "INTERNAL" : null,
141
+ retried: Boolean(error)
142
+ });
131
143
  context.logger?.info("Tx finalized", {
132
144
  txHash: context.txHash,
133
145
  txStatus,
134
146
  txState,
135
147
  error,
136
- timing: context.timer?.summary()
148
+ timing: context.timer?.summary(),
149
+ perfV: 1,
150
+ perf: context.timer?.summaryV2()
137
151
  });
138
152
  if (error) return reject(error);
139
153
  return resolve(context);
@@ -142,7 +156,7 @@ const createExecute = ({ filter, runAsLambda }) => {
142
156
  });
143
157
  if (typeof runAsLambda === "function") return async (context, protocols) => {
144
158
  let ctx = context;
145
- context.timer = new TxTimer();
159
+ context.timer = context.timer || new TxTimer();
146
160
  let entryFinalized = false;
147
161
  let savedLedgerSequence;
148
162
  try {
@@ -161,10 +175,12 @@ const createExecute = ({ filter, runAsLambda }) => {
161
175
  "timer"
162
176
  ]);
163
177
  ctx.txn = txn;
178
+ ctx.timer?.mark("lockWait");
164
179
  await execute(ctx, protocols, true);
165
180
  if (ctx.ledgerSequence && !savedLedgerSequence) savedLedgerSequence = ctx.ledgerSequence;
166
181
  const state = getStates(context).tx.create(ctx, "OK");
167
182
  await context.statedb.tx.create(state.hash, state, ctx);
183
+ ctx.timer?.mark("txstate");
168
184
  return state;
169
185
  }, {
170
186
  cleanWorkingSet: true,
@@ -181,6 +197,7 @@ const createExecute = ({ filter, runAsLambda }) => {
181
197
  stateCommitHash,
182
198
  error: err
183
199
  });
200
+ ctx.timer?.setMeta({ finalizeError: err?.code || "FINALIZE_FAILED" });
184
201
  }
185
202
  }
186
203
  });
@@ -193,11 +210,22 @@ const createExecute = ({ filter, runAsLambda }) => {
193
210
  error: err
194
211
  });
195
212
  });
213
+ ctx.timer?.setMeta({
214
+ txType: ctx.txType,
215
+ txSize: ctx.txSize,
216
+ senderAddr: ctx.tx?.from,
217
+ ledgerSequence: ctx.ledgerSequence,
218
+ status: "OK",
219
+ errorCode: null,
220
+ retried: false
221
+ });
196
222
  ctx.logger?.info("Tx finalized", {
197
223
  txHash: ctx.txHash,
198
224
  txState,
199
225
  txStatus: "OK",
200
- timing: ctx.timer?.summary()
226
+ timing: ctx.timer?.summary(),
227
+ perfV: 1,
228
+ perf: ctx.timer?.summaryV2()
201
229
  });
202
230
  } catch (error) {
203
231
  const err = error;
@@ -217,9 +245,11 @@ const createExecute = ({ filter, runAsLambda }) => {
217
245
  txn,
218
246
  cacheStates: null
219
247
  });
248
+ ctx.timer?.mark("lockWait");
220
249
  await ensureGasFeePaid(ctx);
221
250
  const state = getStates(context).tx.create(ctx, txStatus);
222
251
  await ctx.statedb.tx.create(state.hash, state, ctx);
252
+ ctx.timer?.mark("txstate");
223
253
  return state;
224
254
  }, {
225
255
  cleanWorkingSet: true,
@@ -236,6 +266,7 @@ const createExecute = ({ filter, runAsLambda }) => {
236
266
  stateCommitHash,
237
267
  error: err$1
238
268
  });
269
+ ctx.timer?.setMeta({ finalizeError: err$1?.code || "FINALIZE_FAILED" });
239
270
  }
240
271
  }
241
272
  });
@@ -248,12 +279,23 @@ const createExecute = ({ filter, runAsLambda }) => {
248
279
  error: err$1
249
280
  });
250
281
  });
282
+ ctx.timer?.setMeta({
283
+ txType: ctx.txType,
284
+ txSize: ctx.txSize,
285
+ senderAddr: ctx.tx?.from,
286
+ ledgerSequence: ctx.ledgerSequence,
287
+ status: "PERSISTED_FAILED",
288
+ errorCode: txStatus,
289
+ retried: true
290
+ });
251
291
  ctx.logger?.info("Tx finalized", {
252
292
  txHash: ctx.txHash,
253
293
  txState,
254
294
  txStatus,
255
295
  error,
256
- timing: ctx.timer?.summary()
296
+ timing: ctx.timer?.summary(),
297
+ perfV: 1,
298
+ perf: ctx.timer?.summaryV2()
257
299
  });
258
300
  } catch (innerErr) {
259
301
  ctx.logger?.error("Failed to save invalid transaction to statedb", {
@@ -265,6 +307,24 @@ const createExecute = ({ filter, runAsLambda }) => {
265
307
  });
266
308
  throw error;
267
309
  }
310
+ } else {
311
+ ctx.timer?.setMeta({
312
+ txType: ctx.txType,
313
+ txSize: ctx.txSize,
314
+ senderAddr: ctx.tx?.from,
315
+ ledgerSequence: ctx.ledgerSequence,
316
+ status: "FAILED",
317
+ errorCode: txStatus,
318
+ retried: false
319
+ });
320
+ ctx.logger?.info("Tx rejected", {
321
+ txHash: ctx.txHash,
322
+ txStatus,
323
+ error,
324
+ timing: ctx.timer?.summary(),
325
+ perfV: 1,
326
+ perf: ctx.timer?.summaryV2()
327
+ });
268
328
  }
269
329
  throw error;
270
330
  } finally {
@@ -275,6 +335,7 @@ const createExecute = ({ filter, runAsLambda }) => {
275
335
  const sequence = ctx.ledgerSequence || savedLedgerSequence || context.ledgerSequence;
276
336
  if (ledger && txHash && sequence && txBase64) try {
277
337
  await ledger.finalizeEntry(txHash, "", sequence, txBase64);
338
+ ctx.timer?.setMeta({ forcedFinalize: true });
278
339
  } catch (err) {
279
340
  (ctx.logger || context.logger)?.error("Failed to finalize orphaned ledger entry", {
280
341
  txHash,
@@ -288,7 +349,7 @@ const createExecute = ({ filter, runAsLambda }) => {
288
349
  return ctx;
289
350
  };
290
351
  return async (context, protocols) => {
291
- context.timer = new TxTimer();
352
+ context.timer = context.timer || new TxTimer();
292
353
  const result = await execute(context, protocols);
293
354
  if (result.ledger && result.txHash && result.ledgerSequence && result.txBase64) try {
294
355
  await result.ledger.finalizeEntry(result.txHash, "", result.ledgerSequence, result.txBase64);
package/esm/index.d.mts CHANGED
@@ -1,3 +1,4 @@
1
+ import { COUNTER_NAMES, CounterName, QueueState, STAGE_LABELS, StageLabel, TxMeta, TxStatus, TxTimer, TxTimerSummaryV2 } from "./tx-timer.mjs";
1
2
  import { TokenInput } from "./protocols/trade/transfer-v2.mjs";
2
3
  import { MultiInput } from "./protocols/trade/transfer-v3.mjs";
3
4
  import { TokenInput as TokenInput$1 } from "./protocols/trade/exchange-v2.mjs";
@@ -756,4 +757,4 @@ declare const defaultExecutor: {
756
757
  };
757
758
  declare const execute: (context: unknown, done?: (err: Error | null, res?: unknown) => void) => any;
758
759
  //#endregion
759
- export { WriteLedger, createExecutor, defaultExecutor as default, execute };
760
+ export { COUNTER_NAMES, type CounterName, type QueueState, STAGE_LABELS, type StageLabel, type TxMeta, type TxStatus, TxTimer, type TxTimerSummaryV2, WriteLedger, createExecutor, defaultExecutor as default, execute };
package/esm/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { WriteLedger } from "./pipes/write-ledger.mjs";
2
+ import { COUNTER_NAMES, STAGE_LABELS, TxTimer } from "./tx-timer.mjs";
2
3
  import execute_default from "./execute.mjs";
3
4
  import delegate_default from "./protocols/account/delegate.mjs";
4
5
  import migrate_default from "./protocols/account/migrate.mjs";
@@ -98,4 +99,4 @@ const { execute } = defaultExecutor;
98
99
  var src_default = defaultExecutor;
99
100
 
100
101
  //#endregion
101
- export { WriteLedger, createExecutor, src_default as default, execute };
102
+ export { COUNTER_NAMES, STAGE_LABELS, TxTimer, WriteLedger, createExecutor, src_default as default, execute };
@@ -70,7 +70,6 @@ const WriteLedger = async (context, next) => {
70
70
  timestamp: txTime ? new Date(txTime).getTime() : Date.now(),
71
71
  txExtra
72
72
  };
73
- context.timer?.mark("verify");
74
73
  const entry = await ledger.append(txInput);
75
74
  context.timer?.mark("ledger");
76
75
  context.ledgerSequence = entry.sequence;
@@ -2,16 +2,102 @@
2
2
  /**
3
3
  * Lightweight transaction execution timer.
4
4
  *
5
- * Records named marks at key stages and computes per-stage durations.
6
- * Overhead per mark() call is a single Date.now() invocation (< 1 µs).
5
+ * Records named marks at key stages, counter increments, and tx metadata.
6
+ * Outputs both a flat legacy summary (for existing log consumers) and a
7
+ * structured v2 schema for downstream perf analysis.
8
+ *
9
+ * Overhead per mark/incrCounter/setMeta call is < 200ns.
10
+ *
11
+ * See perfreview/codex/07-txtimer-design.md for the schema rationale.
12
+ */
13
+ /**
14
+ * Canonical stage labels, ordered by typical occurrence.
15
+ * Stage duration = `(mark time) - (previous mark time or origin)`.
16
+ *
17
+ * Not every tx hits every stage:
18
+ * - REJECTED txs stop after `verify` (or earlier).
19
+ * - FAILED txs without persistence stop after the protocol error.
20
+ * - PERSISTED_FAILED txs go through gas-charge runAsLambda and produce a second set.
21
+ */
22
+ declare const STAGE_LABELS: readonly ["queueWait", "decode", "verify", "lockWait", "ledger", "protocolRead", "protocolWrite", "protocolDiff", "txstate", "commit", "indexdb"];
23
+ type StageLabel = (typeof STAGE_LABELS)[number];
24
+ declare const COUNTER_NAMES: readonly ["stateReads", "stateWrites", "tokenWrites", "indexEvents"];
25
+ type CounterName = (typeof COUNTER_NAMES)[number];
26
+ /**
27
+ * - OK committed via the happy-path runAsLambda
28
+ * - PERSISTED_FAILED committed via the gas-charge fallback runAsLambda
29
+ * - FAILED not committed (pre-pipeline reject, signature, replay,
30
+ * or protocol error with persist=false)
31
+ */
32
+ type TxStatus = 'OK' | 'PERSISTED_FAILED' | 'FAILED';
33
+ interface TxMeta {
34
+ txType?: string;
35
+ txSize?: number;
36
+ senderAddr?: string;
37
+ ledgerSequence?: number;
38
+ status?: TxStatus;
39
+ errorCode?: string | null;
40
+ retried?: boolean;
41
+ forcedFinalize?: boolean;
42
+ finalizeError?: string;
43
+ }
44
+ interface QueueState {
45
+ waitingAtEnqueue: number;
46
+ runningAtEnqueue: number;
47
+ concurrencyConfig: number;
48
+ }
49
+ interface TxTimerSummaryV2 {
50
+ stages: Partial<Record<StageLabel, number>> & {
51
+ total: number;
52
+ };
53
+ counters: Record<CounterName, number>;
54
+ meta: TxMeta;
55
+ queue: QueueState | null;
56
+ }
57
+ /**
58
+ * Lightweight transaction execution timer.
59
+ *
60
+ * Backward compatibility:
61
+ * - `mark(label)` and `summary()` keep their original semantics.
62
+ * - Existing log consumers reading the flat `timing` object are unaffected.
63
+ *
64
+ * New API for v2 schema:
65
+ * - `incrCounter(name, delta?)` — bump a named counter (e.g. stateReads)
66
+ * - `setMeta(meta)` — attach tx metadata (txType, status, errorCode, ...)
67
+ * - `setQueueState(qs)` — record resolver queue depth at enqueue
68
+ * - `summaryV2()` — structured per-stage durations + counters + meta
7
69
  */
8
70
  declare class TxTimer {
9
71
  private marks;
10
72
  private origin;
73
+ private counters;
74
+ private meta;
75
+ private queueState;
11
76
  /** Record a named timestamp. */
12
77
  mark(label: string): void;
13
- /** Compute per-stage durations (ms) between consecutive marks. */
78
+ /**
79
+ * Compute per-stage durations (ms) between consecutive marks.
80
+ *
81
+ * Legacy schema: flat object `{ [label]: ms, total: ms }`. If the same label
82
+ * is marked twice, the latest entry wins (matching pre-v2 behavior).
83
+ */
14
84
  summary(): Record<string, number>;
85
+ /** Increment a named counter (default delta = 1). Cheap: ~5ns. */
86
+ incrCounter(name: CounterName | string, delta?: number): void;
87
+ /** Attach or merge tx metadata. */
88
+ setMeta(meta: Partial<TxMeta>): void;
89
+ /** Record resolver queue depth at enqueue time. Set once at sendTx entry. */
90
+ setQueueState(qs: QueueState): void;
91
+ /**
92
+ * Structured v2 schema.
93
+ *
94
+ * Only stages that were marked appear in `stages`. `total` is always
95
+ * present (origin → last mark, or 0 if no marks). Counters always present
96
+ * with 0 default for the canonical names. Unknown marks (not in
97
+ * STAGE_LABELS) are silently dropped from `stages` to keep the schema
98
+ * stable; they still affect `total` and remain in the legacy `summary()`.
99
+ */
100
+ summaryV2(): TxTimerSummaryV2;
15
101
  }
16
102
  //#endregion
17
- export { TxTimer };
103
+ export { COUNTER_NAMES, CounterName, QueueState, STAGE_LABELS, StageLabel, TxMeta, TxStatus, TxTimer, TxTimerSummaryV2 };
package/esm/tx-timer.mjs CHANGED
@@ -2,19 +2,73 @@
2
2
  /**
3
3
  * Lightweight transaction execution timer.
4
4
  *
5
- * Records named marks at key stages and computes per-stage durations.
6
- * Overhead per mark() call is a single Date.now() invocation (< 1 µs).
5
+ * Records named marks at key stages, counter increments, and tx metadata.
6
+ * Outputs both a flat legacy summary (for existing log consumers) and a
7
+ * structured v2 schema for downstream perf analysis.
8
+ *
9
+ * Overhead per mark/incrCounter/setMeta call is < 200ns.
10
+ *
11
+ * See perfreview/codex/07-txtimer-design.md for the schema rationale.
12
+ */
13
+ /**
14
+ * Canonical stage labels, ordered by typical occurrence.
15
+ * Stage duration = `(mark time) - (previous mark time or origin)`.
16
+ *
17
+ * Not every tx hits every stage:
18
+ * - REJECTED txs stop after `verify` (or earlier).
19
+ * - FAILED txs without persistence stop after the protocol error.
20
+ * - PERSISTED_FAILED txs go through gas-charge runAsLambda and produce a second set.
21
+ */
22
+ const STAGE_LABELS = [
23
+ "queueWait",
24
+ "decode",
25
+ "verify",
26
+ "lockWait",
27
+ "ledger",
28
+ "protocolRead",
29
+ "protocolWrite",
30
+ "protocolDiff",
31
+ "txstate",
32
+ "commit",
33
+ "indexdb"
34
+ ];
35
+ const COUNTER_NAMES = [
36
+ "stateReads",
37
+ "stateWrites",
38
+ "tokenWrites",
39
+ "indexEvents"
40
+ ];
41
+ /**
42
+ * Lightweight transaction execution timer.
43
+ *
44
+ * Backward compatibility:
45
+ * - `mark(label)` and `summary()` keep their original semantics.
46
+ * - Existing log consumers reading the flat `timing` object are unaffected.
47
+ *
48
+ * New API for v2 schema:
49
+ * - `incrCounter(name, delta?)` — bump a named counter (e.g. stateReads)
50
+ * - `setMeta(meta)` — attach tx metadata (txType, status, errorCode, ...)
51
+ * - `setQueueState(qs)` — record resolver queue depth at enqueue
52
+ * - `summaryV2()` — structured per-stage durations + counters + meta
7
53
  */
8
54
  var TxTimer = class {
9
55
  constructor() {
10
56
  this.marks = [];
11
57
  this.origin = Date.now();
58
+ this.counters = {};
59
+ this.meta = {};
60
+ this.queueState = null;
12
61
  }
13
62
  /** Record a named timestamp. */
14
63
  mark(label) {
15
64
  this.marks.push([label, Date.now()]);
16
65
  }
17
- /** Compute per-stage durations (ms) between consecutive marks. */
66
+ /**
67
+ * Compute per-stage durations (ms) between consecutive marks.
68
+ *
69
+ * Legacy schema: flat object `{ [label]: ms, total: ms }`. If the same label
70
+ * is marked twice, the latest entry wins (matching pre-v2 behavior).
71
+ */
18
72
  summary() {
19
73
  const result = {};
20
74
  let prev = this.origin;
@@ -25,7 +79,56 @@ var TxTimer = class {
25
79
  result.total = prev - this.origin;
26
80
  return result;
27
81
  }
82
+ /** Increment a named counter (default delta = 1). Cheap: ~5ns. */
83
+ incrCounter(name, delta = 1) {
84
+ this.counters[name] = (this.counters[name] || 0) + delta;
85
+ }
86
+ /** Attach or merge tx metadata. */
87
+ setMeta(meta) {
88
+ Object.assign(this.meta, meta);
89
+ }
90
+ /** Record resolver queue depth at enqueue time. Set once at sendTx entry. */
91
+ setQueueState(qs) {
92
+ this.queueState = qs;
93
+ }
94
+ /**
95
+ * Structured v2 schema.
96
+ *
97
+ * Only stages that were marked appear in `stages`. `total` is always
98
+ * present (origin → last mark, or 0 if no marks). Counters always present
99
+ * with 0 default for the canonical names. Unknown marks (not in
100
+ * STAGE_LABELS) are silently dropped from `stages` to keep the schema
101
+ * stable; they still affect `total` and remain in the legacy `summary()`.
102
+ */
103
+ summaryV2() {
104
+ const known = new Set(STAGE_LABELS);
105
+ const stages = {};
106
+ let prev = this.origin;
107
+ let last = this.origin;
108
+ for (const [label, time] of this.marks) {
109
+ const dur = time - prev;
110
+ if (known.has(label)) stages[label] = dur;
111
+ prev = time;
112
+ last = time;
113
+ }
114
+ const counters = {
115
+ stateReads: 0,
116
+ stateWrites: 0,
117
+ tokenWrites: 0,
118
+ indexEvents: 0
119
+ };
120
+ for (const name of COUNTER_NAMES) counters[name] = this.counters[name] || 0;
121
+ return {
122
+ stages: {
123
+ ...stages,
124
+ total: last - this.origin
125
+ },
126
+ counters,
127
+ meta: { ...this.meta },
128
+ queue: this.queueState ? { ...this.queueState } : null
129
+ };
130
+ }
28
131
  };
29
132
 
30
133
  //#endregion
31
- export { TxTimer };
134
+ export { COUNTER_NAMES, STAGE_LABELS, TxTimer };
package/lib/execute.cjs CHANGED
@@ -31,7 +31,9 @@ const getStates = (context) => {
31
31
  return context.states;
32
32
  };
33
33
  const flushEvents = (context, extra = {}) => {
34
- (context.events || []).forEach((e) => {
34
+ const events = context.events || [];
35
+ if (events.length) context.timer?.incrCounter("indexEvents", events.length);
36
+ events.forEach((e) => {
35
37
  const table = context.statedb[e.table];
36
38
  if (table?.emit) table.emit(e.name, e.data, {
37
39
  ...e.ctx,
@@ -122,6 +124,7 @@ const createExecute = ({ filter, runAsLambda }) => {
122
124
  txState = states.tx.create(context, txStatus);
123
125
  }
124
126
  await context.statedb.tx.create(txState.hash, txState, context);
127
+ context.timer?.mark("txstate");
125
128
  context.timer?.mark("commit");
126
129
  flushEvents(context, { txState });
127
130
  context.timer?.mark("indexdb");
@@ -134,12 +137,23 @@ const createExecute = ({ filter, runAsLambda }) => {
134
137
  });
135
138
  return reject(error);
136
139
  }
140
+ context.timer?.setMeta({
141
+ txType: context.txType,
142
+ txSize: context.txSize,
143
+ senderAddr: context.tx?.from,
144
+ ledgerSequence: context.ledgerSequence,
145
+ status: error ? shouldPersistTx(error) ? "PERSISTED_FAILED" : "FAILED" : "OK",
146
+ errorCode: error ? error.code || "INTERNAL" : null,
147
+ retried: Boolean(error)
148
+ });
137
149
  context.logger?.info("Tx finalized", {
138
150
  txHash: context.txHash,
139
151
  txStatus,
140
152
  txState,
141
153
  error,
142
- timing: context.timer?.summary()
154
+ timing: context.timer?.summary(),
155
+ perfV: 1,
156
+ perf: context.timer?.summaryV2()
143
157
  });
144
158
  if (error) return reject(error);
145
159
  return resolve(context);
@@ -148,7 +162,7 @@ const createExecute = ({ filter, runAsLambda }) => {
148
162
  });
149
163
  if (typeof runAsLambda === "function") return async (context, protocols) => {
150
164
  let ctx = context;
151
- context.timer = new require_tx_timer.TxTimer();
165
+ context.timer = context.timer || new require_tx_timer.TxTimer();
152
166
  let entryFinalized = false;
153
167
  let savedLedgerSequence;
154
168
  try {
@@ -167,10 +181,12 @@ const createExecute = ({ filter, runAsLambda }) => {
167
181
  "timer"
168
182
  ]);
169
183
  ctx.txn = txn;
184
+ ctx.timer?.mark("lockWait");
170
185
  await execute(ctx, protocols, true);
171
186
  if (ctx.ledgerSequence && !savedLedgerSequence) savedLedgerSequence = ctx.ledgerSequence;
172
187
  const state = getStates(context).tx.create(ctx, "OK");
173
188
  await context.statedb.tx.create(state.hash, state, ctx);
189
+ ctx.timer?.mark("txstate");
174
190
  return state;
175
191
  }, {
176
192
  cleanWorkingSet: true,
@@ -187,6 +203,7 @@ const createExecute = ({ filter, runAsLambda }) => {
187
203
  stateCommitHash,
188
204
  error: err
189
205
  });
206
+ ctx.timer?.setMeta({ finalizeError: err?.code || "FINALIZE_FAILED" });
190
207
  }
191
208
  }
192
209
  });
@@ -199,11 +216,22 @@ const createExecute = ({ filter, runAsLambda }) => {
199
216
  error: err
200
217
  });
201
218
  });
219
+ ctx.timer?.setMeta({
220
+ txType: ctx.txType,
221
+ txSize: ctx.txSize,
222
+ senderAddr: ctx.tx?.from,
223
+ ledgerSequence: ctx.ledgerSequence,
224
+ status: "OK",
225
+ errorCode: null,
226
+ retried: false
227
+ });
202
228
  ctx.logger?.info("Tx finalized", {
203
229
  txHash: ctx.txHash,
204
230
  txState,
205
231
  txStatus: "OK",
206
- timing: ctx.timer?.summary()
232
+ timing: ctx.timer?.summary(),
233
+ perfV: 1,
234
+ perf: ctx.timer?.summaryV2()
207
235
  });
208
236
  } catch (error) {
209
237
  const err = error;
@@ -223,9 +251,11 @@ const createExecute = ({ filter, runAsLambda }) => {
223
251
  txn,
224
252
  cacheStates: null
225
253
  });
254
+ ctx.timer?.mark("lockWait");
226
255
  await ensureGasFeePaid(ctx);
227
256
  const state = getStates(context).tx.create(ctx, txStatus);
228
257
  await ctx.statedb.tx.create(state.hash, state, ctx);
258
+ ctx.timer?.mark("txstate");
229
259
  return state;
230
260
  }, {
231
261
  cleanWorkingSet: true,
@@ -242,6 +272,7 @@ const createExecute = ({ filter, runAsLambda }) => {
242
272
  stateCommitHash,
243
273
  error: err$1
244
274
  });
275
+ ctx.timer?.setMeta({ finalizeError: err$1?.code || "FINALIZE_FAILED" });
245
276
  }
246
277
  }
247
278
  });
@@ -254,12 +285,23 @@ const createExecute = ({ filter, runAsLambda }) => {
254
285
  error: err$1
255
286
  });
256
287
  });
288
+ ctx.timer?.setMeta({
289
+ txType: ctx.txType,
290
+ txSize: ctx.txSize,
291
+ senderAddr: ctx.tx?.from,
292
+ ledgerSequence: ctx.ledgerSequence,
293
+ status: "PERSISTED_FAILED",
294
+ errorCode: txStatus,
295
+ retried: true
296
+ });
257
297
  ctx.logger?.info("Tx finalized", {
258
298
  txHash: ctx.txHash,
259
299
  txState,
260
300
  txStatus,
261
301
  error,
262
- timing: ctx.timer?.summary()
302
+ timing: ctx.timer?.summary(),
303
+ perfV: 1,
304
+ perf: ctx.timer?.summaryV2()
263
305
  });
264
306
  } catch (innerErr) {
265
307
  ctx.logger?.error("Failed to save invalid transaction to statedb", {
@@ -271,6 +313,24 @@ const createExecute = ({ filter, runAsLambda }) => {
271
313
  });
272
314
  throw error;
273
315
  }
316
+ } else {
317
+ ctx.timer?.setMeta({
318
+ txType: ctx.txType,
319
+ txSize: ctx.txSize,
320
+ senderAddr: ctx.tx?.from,
321
+ ledgerSequence: ctx.ledgerSequence,
322
+ status: "FAILED",
323
+ errorCode: txStatus,
324
+ retried: false
325
+ });
326
+ ctx.logger?.info("Tx rejected", {
327
+ txHash: ctx.txHash,
328
+ txStatus,
329
+ error,
330
+ timing: ctx.timer?.summary(),
331
+ perfV: 1,
332
+ perf: ctx.timer?.summaryV2()
333
+ });
274
334
  }
275
335
  throw error;
276
336
  } finally {
@@ -281,6 +341,7 @@ const createExecute = ({ filter, runAsLambda }) => {
281
341
  const sequence = ctx.ledgerSequence || savedLedgerSequence || context.ledgerSequence;
282
342
  if (ledger && txHash && sequence && txBase64) try {
283
343
  await ledger.finalizeEntry(txHash, "", sequence, txBase64);
344
+ ctx.timer?.setMeta({ forcedFinalize: true });
284
345
  } catch (err) {
285
346
  (ctx.logger || context.logger)?.error("Failed to finalize orphaned ledger entry", {
286
347
  txHash,
@@ -294,7 +355,7 @@ const createExecute = ({ filter, runAsLambda }) => {
294
355
  return ctx;
295
356
  };
296
357
  return async (context, protocols) => {
297
- context.timer = new require_tx_timer.TxTimer();
358
+ context.timer = context.timer || new require_tx_timer.TxTimer();
298
359
  const result = await execute(context, protocols);
299
360
  if (result.ledger && result.txHash && result.ledgerSequence && result.txBase64) try {
300
361
  await result.ledger.finalizeEntry(result.txHash, "", result.ledgerSequence, result.txBase64);
package/lib/index.cjs CHANGED
@@ -1,6 +1,7 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
  const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
3
3
  const require_pipes_write_ledger = require('./pipes/write-ledger.cjs');
4
+ const require_tx_timer = require('./tx-timer.cjs');
4
5
  const require_execute = require('./execute.cjs');
5
6
  const require_protocols_account_delegate = require('./protocols/account/delegate.cjs');
6
7
  const require_protocols_account_migrate = require('./protocols/account/migrate.cjs');
@@ -101,6 +102,9 @@ const { execute } = defaultExecutor;
101
102
  var src_default = defaultExecutor;
102
103
 
103
104
  //#endregion
105
+ exports.COUNTER_NAMES = require_tx_timer.COUNTER_NAMES;
106
+ exports.STAGE_LABELS = require_tx_timer.STAGE_LABELS;
107
+ exports.TxTimer = require_tx_timer.TxTimer;
104
108
  exports.WriteLedger = require_pipes_write_ledger.WriteLedger;
105
109
  exports.createExecutor = createExecutor;
106
110
  exports.default = src_default;
package/lib/index.d.cts CHANGED
@@ -1,3 +1,4 @@
1
+ import { COUNTER_NAMES, CounterName, QueueState, STAGE_LABELS, StageLabel, TxMeta, TxStatus, TxTimer, TxTimerSummaryV2 } from "./tx-timer.cjs";
1
2
  import { TokenInput } from "./protocols/trade/transfer-v2.cjs";
2
3
  import { MultiInput } from "./protocols/trade/transfer-v3.cjs";
3
4
  import { TokenInput as TokenInput$1 } from "./protocols/trade/exchange-v2.cjs";
@@ -756,4 +757,4 @@ declare const defaultExecutor: {
756
757
  };
757
758
  declare const execute: (context: unknown, done?: (err: Error | null, res?: unknown) => void) => any;
758
759
  //#endregion
759
- export { WriteLedger, createExecutor, defaultExecutor as default, execute };
760
+ export { COUNTER_NAMES, type CounterName, type QueueState, STAGE_LABELS, type StageLabel, type TxMeta, type TxStatus, TxTimer, type TxTimerSummaryV2, WriteLedger, createExecutor, defaultExecutor as default, execute };
@@ -73,7 +73,6 @@ const WriteLedger = async (context, next) => {
73
73
  timestamp: txTime ? new Date(txTime).getTime() : Date.now(),
74
74
  txExtra
75
75
  };
76
- context.timer?.mark("verify");
77
76
  const entry = await ledger.append(txInput);
78
77
  context.timer?.mark("ledger");
79
78
  context.ledgerSequence = entry.sequence;
package/lib/tx-timer.cjs CHANGED
@@ -3,19 +3,73 @@
3
3
  /**
4
4
  * Lightweight transaction execution timer.
5
5
  *
6
- * Records named marks at key stages and computes per-stage durations.
7
- * Overhead per mark() call is a single Date.now() invocation (< 1 µs).
6
+ * Records named marks at key stages, counter increments, and tx metadata.
7
+ * Outputs both a flat legacy summary (for existing log consumers) and a
8
+ * structured v2 schema for downstream perf analysis.
9
+ *
10
+ * Overhead per mark/incrCounter/setMeta call is < 200ns.
11
+ *
12
+ * See perfreview/codex/07-txtimer-design.md for the schema rationale.
13
+ */
14
+ /**
15
+ * Canonical stage labels, ordered by typical occurrence.
16
+ * Stage duration = `(mark time) - (previous mark time or origin)`.
17
+ *
18
+ * Not every tx hits every stage:
19
+ * - REJECTED txs stop after `verify` (or earlier).
20
+ * - FAILED txs without persistence stop after the protocol error.
21
+ * - PERSISTED_FAILED txs go through gas-charge runAsLambda and produce a second set.
22
+ */
23
+ const STAGE_LABELS = [
24
+ "queueWait",
25
+ "decode",
26
+ "verify",
27
+ "lockWait",
28
+ "ledger",
29
+ "protocolRead",
30
+ "protocolWrite",
31
+ "protocolDiff",
32
+ "txstate",
33
+ "commit",
34
+ "indexdb"
35
+ ];
36
+ const COUNTER_NAMES = [
37
+ "stateReads",
38
+ "stateWrites",
39
+ "tokenWrites",
40
+ "indexEvents"
41
+ ];
42
+ /**
43
+ * Lightweight transaction execution timer.
44
+ *
45
+ * Backward compatibility:
46
+ * - `mark(label)` and `summary()` keep their original semantics.
47
+ * - Existing log consumers reading the flat `timing` object are unaffected.
48
+ *
49
+ * New API for v2 schema:
50
+ * - `incrCounter(name, delta?)` — bump a named counter (e.g. stateReads)
51
+ * - `setMeta(meta)` — attach tx metadata (txType, status, errorCode, ...)
52
+ * - `setQueueState(qs)` — record resolver queue depth at enqueue
53
+ * - `summaryV2()` — structured per-stage durations + counters + meta
8
54
  */
9
55
  var TxTimer = class {
10
56
  constructor() {
11
57
  this.marks = [];
12
58
  this.origin = Date.now();
59
+ this.counters = {};
60
+ this.meta = {};
61
+ this.queueState = null;
13
62
  }
14
63
  /** Record a named timestamp. */
15
64
  mark(label) {
16
65
  this.marks.push([label, Date.now()]);
17
66
  }
18
- /** Compute per-stage durations (ms) between consecutive marks. */
67
+ /**
68
+ * Compute per-stage durations (ms) between consecutive marks.
69
+ *
70
+ * Legacy schema: flat object `{ [label]: ms, total: ms }`. If the same label
71
+ * is marked twice, the latest entry wins (matching pre-v2 behavior).
72
+ */
19
73
  summary() {
20
74
  const result = {};
21
75
  let prev = this.origin;
@@ -26,7 +80,58 @@ var TxTimer = class {
26
80
  result.total = prev - this.origin;
27
81
  return result;
28
82
  }
83
+ /** Increment a named counter (default delta = 1). Cheap: ~5ns. */
84
+ incrCounter(name, delta = 1) {
85
+ this.counters[name] = (this.counters[name] || 0) + delta;
86
+ }
87
+ /** Attach or merge tx metadata. */
88
+ setMeta(meta) {
89
+ Object.assign(this.meta, meta);
90
+ }
91
+ /** Record resolver queue depth at enqueue time. Set once at sendTx entry. */
92
+ setQueueState(qs) {
93
+ this.queueState = qs;
94
+ }
95
+ /**
96
+ * Structured v2 schema.
97
+ *
98
+ * Only stages that were marked appear in `stages`. `total` is always
99
+ * present (origin → last mark, or 0 if no marks). Counters always present
100
+ * with 0 default for the canonical names. Unknown marks (not in
101
+ * STAGE_LABELS) are silently dropped from `stages` to keep the schema
102
+ * stable; they still affect `total` and remain in the legacy `summary()`.
103
+ */
104
+ summaryV2() {
105
+ const known = new Set(STAGE_LABELS);
106
+ const stages = {};
107
+ let prev = this.origin;
108
+ let last = this.origin;
109
+ for (const [label, time] of this.marks) {
110
+ const dur = time - prev;
111
+ if (known.has(label)) stages[label] = dur;
112
+ prev = time;
113
+ last = time;
114
+ }
115
+ const counters = {
116
+ stateReads: 0,
117
+ stateWrites: 0,
118
+ tokenWrites: 0,
119
+ indexEvents: 0
120
+ };
121
+ for (const name of COUNTER_NAMES) counters[name] = this.counters[name] || 0;
122
+ return {
123
+ stages: {
124
+ ...stages,
125
+ total: last - this.origin
126
+ },
127
+ counters,
128
+ meta: { ...this.meta },
129
+ queue: this.queueState ? { ...this.queueState } : null
130
+ };
131
+ }
29
132
  };
30
133
 
31
134
  //#endregion
135
+ exports.COUNTER_NAMES = COUNTER_NAMES;
136
+ exports.STAGE_LABELS = STAGE_LABELS;
32
137
  exports.TxTimer = TxTimer;
@@ -2,16 +2,102 @@
2
2
  /**
3
3
  * Lightweight transaction execution timer.
4
4
  *
5
- * Records named marks at key stages and computes per-stage durations.
6
- * Overhead per mark() call is a single Date.now() invocation (< 1 µs).
5
+ * Records named marks at key stages, counter increments, and tx metadata.
6
+ * Outputs both a flat legacy summary (for existing log consumers) and a
7
+ * structured v2 schema for downstream perf analysis.
8
+ *
9
+ * Overhead per mark/incrCounter/setMeta call is < 200ns.
10
+ *
11
+ * See perfreview/codex/07-txtimer-design.md for the schema rationale.
12
+ */
13
+ /**
14
+ * Canonical stage labels, ordered by typical occurrence.
15
+ * Stage duration = `(mark time) - (previous mark time or origin)`.
16
+ *
17
+ * Not every tx hits every stage:
18
+ * - REJECTED txs stop after `verify` (or earlier).
19
+ * - FAILED txs without persistence stop after the protocol error.
20
+ * - PERSISTED_FAILED txs go through gas-charge runAsLambda and produce a second set.
21
+ */
22
+ declare const STAGE_LABELS: readonly ["queueWait", "decode", "verify", "lockWait", "ledger", "protocolRead", "protocolWrite", "protocolDiff", "txstate", "commit", "indexdb"];
23
+ type StageLabel = (typeof STAGE_LABELS)[number];
24
+ declare const COUNTER_NAMES: readonly ["stateReads", "stateWrites", "tokenWrites", "indexEvents"];
25
+ type CounterName = (typeof COUNTER_NAMES)[number];
26
+ /**
27
+ * - OK committed via the happy-path runAsLambda
28
+ * - PERSISTED_FAILED committed via the gas-charge fallback runAsLambda
29
+ * - FAILED not committed (pre-pipeline reject, signature, replay,
30
+ * or protocol error with persist=false)
31
+ */
32
+ type TxStatus = 'OK' | 'PERSISTED_FAILED' | 'FAILED';
33
+ interface TxMeta {
34
+ txType?: string;
35
+ txSize?: number;
36
+ senderAddr?: string;
37
+ ledgerSequence?: number;
38
+ status?: TxStatus;
39
+ errorCode?: string | null;
40
+ retried?: boolean;
41
+ forcedFinalize?: boolean;
42
+ finalizeError?: string;
43
+ }
44
+ interface QueueState {
45
+ waitingAtEnqueue: number;
46
+ runningAtEnqueue: number;
47
+ concurrencyConfig: number;
48
+ }
49
+ interface TxTimerSummaryV2 {
50
+ stages: Partial<Record<StageLabel, number>> & {
51
+ total: number;
52
+ };
53
+ counters: Record<CounterName, number>;
54
+ meta: TxMeta;
55
+ queue: QueueState | null;
56
+ }
57
+ /**
58
+ * Lightweight transaction execution timer.
59
+ *
60
+ * Backward compatibility:
61
+ * - `mark(label)` and `summary()` keep their original semantics.
62
+ * - Existing log consumers reading the flat `timing` object are unaffected.
63
+ *
64
+ * New API for v2 schema:
65
+ * - `incrCounter(name, delta?)` — bump a named counter (e.g. stateReads)
66
+ * - `setMeta(meta)` — attach tx metadata (txType, status, errorCode, ...)
67
+ * - `setQueueState(qs)` — record resolver queue depth at enqueue
68
+ * - `summaryV2()` — structured per-stage durations + counters + meta
7
69
  */
8
70
  declare class TxTimer {
9
71
  private marks;
10
72
  private origin;
73
+ private counters;
74
+ private meta;
75
+ private queueState;
11
76
  /** Record a named timestamp. */
12
77
  mark(label: string): void;
13
- /** Compute per-stage durations (ms) between consecutive marks. */
78
+ /**
79
+ * Compute per-stage durations (ms) between consecutive marks.
80
+ *
81
+ * Legacy schema: flat object `{ [label]: ms, total: ms }`. If the same label
82
+ * is marked twice, the latest entry wins (matching pre-v2 behavior).
83
+ */
14
84
  summary(): Record<string, number>;
85
+ /** Increment a named counter (default delta = 1). Cheap: ~5ns. */
86
+ incrCounter(name: CounterName | string, delta?: number): void;
87
+ /** Attach or merge tx metadata. */
88
+ setMeta(meta: Partial<TxMeta>): void;
89
+ /** Record resolver queue depth at enqueue time. Set once at sendTx entry. */
90
+ setQueueState(qs: QueueState): void;
91
+ /**
92
+ * Structured v2 schema.
93
+ *
94
+ * Only stages that were marked appear in `stages`. `total` is always
95
+ * present (origin → last mark, or 0 if no marks). Counters always present
96
+ * with 0 default for the canonical names. Unknown marks (not in
97
+ * STAGE_LABELS) are silently dropped from `stages` to keep the schema
98
+ * stable; they still affect `total` and remain in the legacy `summary()`.
99
+ */
100
+ summaryV2(): TxTimerSummaryV2;
15
101
  }
16
102
  //#endregion
17
- export { TxTimer };
103
+ export { COUNTER_NAMES, CounterName, QueueState, STAGE_LABELS, StageLabel, TxMeta, TxStatus, TxTimer, TxTimerSummaryV2 };
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.30.10",
6
+ "version": "1.30.11",
7
7
  "description": "Predefined tx pipeline sets to execute certain type of transactions",
8
8
  "type": "module",
9
9
  "main": "./lib/index.cjs",
@@ -46,22 +46,22 @@
46
46
  "author": "wangshijun <wangshijun2010@gmail.com> (http://github.com/wangshijun)",
47
47
  "license": "MIT",
48
48
  "dependencies": {
49
- "@arcblock/did": "1.30.10",
50
- "@arcblock/did-util": "1.30.10",
51
- "@arcblock/jwt": "1.30.10",
52
- "@arcblock/validator": "1.30.10",
53
- "@arcblock/vc": "1.30.10",
49
+ "@arcblock/did": "1.30.11",
50
+ "@arcblock/did-util": "1.30.11",
51
+ "@arcblock/jwt": "1.30.11",
52
+ "@arcblock/validator": "1.30.11",
53
+ "@arcblock/vc": "1.30.11",
54
54
  "@blocklet/xss": "^0.3.7",
55
- "@ocap/asset": "1.30.10",
56
- "@ocap/client": "1.30.10",
57
- "@ocap/mcrypto": "1.30.10",
58
- "@ocap/merkle-tree": "1.30.10",
59
- "@ocap/message": "1.30.10",
60
- "@ocap/state": "1.30.10",
61
- "@ocap/tx-pipeline": "1.30.10",
62
- "@ocap/types": "1.30.10",
63
- "@ocap/util": "1.30.10",
64
- "@ocap/wallet": "1.30.10",
55
+ "@ocap/asset": "1.30.11",
56
+ "@ocap/client": "1.30.11",
57
+ "@ocap/mcrypto": "1.30.11",
58
+ "@ocap/merkle-tree": "1.30.11",
59
+ "@ocap/message": "1.30.11",
60
+ "@ocap/state": "1.30.11",
61
+ "@ocap/tx-pipeline": "1.30.11",
62
+ "@ocap/types": "1.30.11",
63
+ "@ocap/util": "1.30.11",
64
+ "@ocap/wallet": "1.30.11",
65
65
  "debug": "^4.4.3",
66
66
  "deep-diff": "^1.0.2",
67
67
  "lodash": "^4.17.23",
package/tools/fixtures.ts CHANGED
@@ -102,6 +102,42 @@ export const signTxForEncoding = async (tx: any, wallet: any, encoding: TxEncodi
102
102
  return { ...stripped, signature };
103
103
  };
104
104
 
105
+ export const forgeMultiSigV2Tx = async ({
106
+ tx,
107
+ signer,
108
+ wallet,
109
+ delegator = '',
110
+ encoding = 'cbor',
111
+ }: {
112
+ tx: any;
113
+ signer: string;
114
+ wallet: any;
115
+ delegator?: string;
116
+ encoding?: TxEncoding;
117
+ }) => {
118
+ const forged = cloneDeep(tx);
119
+ const signatures = forged.signatures || forged.signaturesList || [];
120
+ const item = signatures.find(
121
+ (sig: any) => sig.signer === signer && (delegator ? sig.delegator === delegator : true)
122
+ );
123
+ if (!item) {
124
+ throw new Error(`Signature item for ${delegator || signer} not found`);
125
+ }
126
+
127
+ item.pk = wallet.publicKey;
128
+ item.signature = '';
129
+
130
+ const signingTx = cloneDeep(forged);
131
+ signingTx.signature = undefined;
132
+ signingTx.signatures = (signingTx.signatures || signingTx.signaturesList || []).map(
133
+ ({ signature, ...sig }: any) => sig
134
+ );
135
+ delete signingTx.signaturesList;
136
+
137
+ item.signature = await wallet.sign(encodeTxBytes(signingTx, encoding));
138
+ return forged;
139
+ };
140
+
105
141
  const context = { txHash: getTxHash(), txTime: new Date().toISOString() };
106
142
  const defaultAttrs = {
107
143
  asset: {